Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an arrayList in Java an array or a list? [closed]

Recently I worked with arrayLists in a Java program I had to write for school. I was simply wondering; is an arrayList an array or a list, or both?


2 Answers

You ask:

is an arrayList an array or a list, or both?


It is a List through inheritance, and it is composed with an array.


It implements the java.util.List<T> interface and thus passes the "is-a" test for this. This means that anything you can do with a List, including calling all of List public methods, you can do with an ArrayList.

It's data model however is backed by an array, and so it contains an array by composition. So this means that while it has some array-like behaviors obtained from the underlying array, you can't call array methods or obtain array fields on it directly. For instance, you cannot obtain items from the ArrayList using array indices. i.e., this won't work: myArrayList[i], but you can call this indirectly via ArrayList's get(int i) method. And also you can't get a length field from it, but you can get it indirectly from its size() method. Also, note that obtaining data from an ArrayList will follow the same limiting big O behavior as that of an array.

like image 51
Hovercraft Full Of Eels Avatar answered Feb 09 '26 13:02

Hovercraft Full Of Eels


ArrayList implements the List interface

See doc: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

If you look at the ArrayList inner implementation, you will notice that it is wrapped around an array.

Here is the implementation for your reference: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java

For instance here is one constructor implementation:

when you create a new ArrayList with initial capacity

public More ...ArrayList(int initialCapacity) {
         super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                                initialCapacity);
        this.elementData = new Object[initialCapacity];
     }
like image 21
Saher Ahwal Avatar answered Feb 09 '26 13:02

Saher Ahwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!