ArrayList and the role of the interface seen from List

I am a new graduate engineer at a web company. I mainly develop Android on a daily basis.

The beginning of the matter in the first place

The other day, Mr. Mentor rushed into the following Java code (Android).

ArrayList<Hoge> hoges = new ArrayList<>();

Mentor "Why is hoges declared in ArrayList? Why not make it List?"

When asked, I couldn't answer.

ArrayList is necessary to store multiple instances of Hoge, and it is natural that the variable to put the ArrayList is declared in ArrayList. .. ..

However, after receiving the explanation, I was convinced by myself, so I would like to summarize it for my own understanding.

List and ArrayList

First, I will summarize the relationship between List and ArrayList.

List List is an interface. An interface is a set of specifications about what methods a class has, and a List is a specification that defines what methods are needed to realize a collection.

Looking at the contents of the source (excerpt of only some methods)

public interface List<E> extends Collection<E> {
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator<E> iterator();
    boolean add(E e);
    boolean remove(Object o);
    boolean equals(Object o);
・
・
・
            etc...

And so on, the methods without logic are put together.

ArrayList When the source of ArrayList is excerpted (only the one corresponding to the method of List above is excerpted)

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
       public int size() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
            return this.size;
       }

       public boolean isEmpty() {
            return size == 0;
       }

       public boolean contains(Object o) {
            return indexOf(o) >= 0;
       }

       public Iterator<E> iterator() {
            return listIterator();
       }

       public boolean add(E e) {
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            elementData[size++] = e;
            return true;
       }

       public boolean remove(Object o) {
            if (o == null) {
                for (int index = 0; index < size; index++)
                    if (elementData[index] == null) {
                        fastRemove(index);
                        return true;
                    }
            } else {
                for (int index = 0; index < size; index++)
                    if (o.equals(elementData[index])) {
                        fastRemove(index);
                        return true;
                    }
                }
            }
            return false;
       }

       public boolean contains(Object o) {
            return indexOf(o) >= 0;
       }

・
・
・
                   etc...

As you can see, in the class that implements the List interface, the process is described in the method that was not contained in List. Also, as you can see after implements, ArrayList has various other methods because it implements RandomAccess, Cloneable, java.io.Serializable as well as List.

By the way, there are many classes that implement List, such as Stack, Vector, LinkedList, in addition to ArrayList. ArrayList is one of the classes that implements the methods defined by List.

What makes you happy with the interface?

The story is a little derailed, but what is the advantage of implementing the actual processing on the implementation class side because the method specifications are summarized?

The point is that the caller of the class does not need to be aware of the contents of the implementation. For example, if you have the following interface:

public interface FileReader {
    void open();
    void close();
    void read();
}

Let's assume that CSVFileReader and JSONFileReader implement this FileReader.

public class CSVFileReader {

    public void open() {
Process to open csv nicely
    }

    public void close() {
Processing that closes csv nicely
    }

    public void read() {
Processing that reads csv nicely
    }

}
public class JSONFileReader {

    public void open() {
Processing to open JSON nicely
    }

    public void close() {
Processing that closes JSON nicely
    }

    public void read() {
Processing that reads JSON nicely
    }

}

Suppose you have a method that takes these classes as arguments and counts the number of characters in the file.

public int getCount(FileReader fileReader) {
    int count = 0;
    while(true) {
        fileReader.read();
        //It is assumed that there is logic around here to exit the loop when the end condition is met.
        count++;
    }
    return count; 
}

The interface only defines the method and cannot be instantiated as it is. However, you can declare it as a type.

In other words, no matter what the implementation of read () is, you can use a class that implements FileReader as long as you know the caller read (). The caller does not need to know if the content to be read is CSV or JSON.

In this way, the mechanism that unifies the calling logic, that is, creates a common main routine, is called polymorphism.

Why declare with that type?

I summarized the relationship between List and ArrayList

Earlier

ArrayList<Hoge> hoges = new ArrayList<>();

Think about how to write.

According to the idea of polymorphism,

List<Hoge> hoges = new ArrayList<>();

Can be written.

ArrayList method

boolean add(E e);
boolean remove(Object o);
boolean equals(Object o);

Etc. are defined in List as an interface and implement it. For example

List<Hoge> hoges = new LinkedList<>();

And even if you store an instance of LinkedList in hoges

hoges.add(hoge);

You can call the same method like this. As I explained earlier in the advantages of the interface, If there is a method that takes a List as an argument, it can be received by ArrayList, LinkedList, or Stack, which increases flexibility.

of course,

ArrayList<Hoge> hoges = new ArrayList<>();

It does not mean that writing is totally useless. Of course, ArrayList also implements RandomAccess, Cloneable, java.io.Serializable, and if you need to use the methods defined in them, you need to declare them in ArrayList.

Otherwise

List<Hoge> hoges = new ArrayList<>();

It would be better to write.

Summary

If you search by List and ArrayList,

List<Hoge> hoges = new ArrayList<>();

I can find an article saying that is better, I think the important thing here is not to memorize the whole thing, but to explain why you make that declaration.

So, this time, I took List and ArrayList as examples and summarized the reasons why I do so.

I think there are still many strange things about studying Java. Tsukkomi, we look forward to hearing from you.

reference

Basics of Java that can be understood in 3 minutes] I tried to summarize the differences between List and ArrayList http://www.sejuku.net/blog/14886

Difference between Java, List and ArrayList. http://piyopiyocs.blog115.fc2.com/blog-entry-219.html

List(JavaPlatform SE 7) http://docs.oracle.com/javase/jp/7/api/java/util/List.html

What is an interface? -The role is different from inheritance- | Let's review object-oriented programming (OOP) (3) https://www.gixo.jp/blog/5159/

Akira Hirasawa Why make it object-oriented 2nd edition Nikkei BP

Recommended Posts

ArrayList and the role of the interface seen from List
[Java] Contents of Collection interface and List interface
Java language from the perspective of Kotlin and C #
Extract a specific element from the list of objects
Difference between List and ArrayList
Java beginners briefly summarized the behavior of Array and ArrayList
Aggregate the number of people every 10 years from List <Person>
[Java] I thought about the merits and uses of "interface"
[Java] Delete the elements of List
Efficiently extract multiple elements from the list randomly and without duplication
I read the source of ArrayList I read
This and that of the JDK
Official logo list of the service
About the role of the initialize method
About removeAll and retainAll of ArrayList
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
Confirmation and refactoring of the flow from request to controller in [httpclient]
[Ruby basics] About the role of true and break in the while statement
Comparison of nullable, non-nullable, non-nullable and safe types from the perspective of null safety
I translated the grammar of R and Java [Updated from time to time]
Significance of interface learned from Java Collection
[Challenge CircleCI from 0] Learn the basics of CircleCI
Folding and unfolding the contents of the Recyclerview
About the operation of next () and nextLine ()
[Challenge Docker from 0] Overview and terms of Docker
The story of RxJava suffering from NoSuchElementException
Ruby from the perspective of other languages
Find the average age from List <Person>.
[Java / Swift] Comparison of Java Interface and Swift Protocol
How to sort the List of SelectItem
Proper use of interface and abstract class
[Java 7] Divide the Java list and execute the process
About the mechanism of the Web and HTTP
Find the difference from a multiple of 10
Check the operation of the interface through threads
Output the sum of each name and its contents from a multiple array
I want to recursively get the superclass and interface of a certain class
[No.004] Corrected the order list screen of the orderer
Has the content of useBodyEncodingForURI changed from Tomcat8?
Check the version of the JDK installed and the version of the JDK enabled
Think about the combination of Servlet and Ajax
Add empty data to the top of the list
Compare the speed of the for statement and the extended for statement.
Ominous odor list suggesting the possibility of refactoring
[Java] The confusing part of String and StringBuilder
I compared the characteristics of Java and .NET
Learn the rudimentary mechanism and usage of Gradle 4.4
About next () and nextLine () of the Scanner class
What are the advantages of DI and Thymeleaf?
Clone and duplicate the app from GitHub (initialization)
Takes out the HashMap value and returns the result sorted by the value of value as a list.
Simple statistical analysis of monetary value from the list searched by Mercari Java development
Divide into arbitrary numbers from the latitude and longitude of north, south, east and west