DrusePstrago
DrusePstrago

Reputation: 119

default size of ArrayList isn't being applied

I am having hard time understanding why the size of ArrayList is zero by default here as opposed to what I have seen on different article that it is actually 10. And even if I change the size, it doesn't get affected.

import java.util.ArrayList;
Class Test{
    private static final ArrayList<Long> foo = new ArrayList<>(1000);
   
    public static void main(String[] args) {
        System.out.println(foo.size());
}

Can anyone explain this?

Upvotes: 0

Views: 500

Answers (2)

Konrad H&#246;ffner
Konrad H&#246;ffner

Reputation: 12207

You have to differentiate between the data structure interface you are using, which is that of a java.util.List and its internal implementation, which is that of a java.util.ArrayList which means it is backed by an array with an initial capacity that will get recreated if its capacity is not enough to hold all the elements.

The constructor ArrayList<T>(int n) does not create a java.util.List with size n, but instead an empty java.util.List (size 0), with it's implementation java.util.ArrayList creating an internal backing array of size n.

However List#size is a method of the interface and reports the size of the list, not the size of the internal backing array, which it does not know about.

Accordingly, if you want to access element 10, you correctly get an exception, because you did not add any elements to the list yet.

If you want to initialize it with n zeroes, see How can I initialize an ArrayList with all zeroes in Java?.

Upvotes: 2

Ihdina
Ihdina

Reputation: 1760

Size of an Array

We created an Integer array of size 1000, which resulted in the below

Integer[] a = new Integer[1000]; 
System.out.println("Size of the Array: " + a.length);

Result:

Size of the Array: 1000

Capacity of an ArrayList

We created an ArrayList of size 1000, which resulted in the below

List<Integer> a = new ArrayList<>(1000);
System.out.println("Size of the ArrayList : " + a.size());

Result:

Size of the ArrayList : 0

As no elements have been added then the size is 0.

Add an element to the ArrayList and check the size

List<Integer> a = new ArrayList<>(1000);
a.add(1);
System.out.println("Size of the ArrayList : " + a.size());

Result:

Size of the ArrayList : 1

Arrays are fixed size but ArrayList are resize size

Upvotes: 1

Related Questions