Indeed ItIs
Indeed ItIs

Reputation: 257

ArrayList resize the current underlying array or creates a new one?

ArrayList resizes the current underlying array or creates a new one? I have read sometimes referring to "the resizeable array" of an ArrayList, however I thought it gets created a new one each time it gets "resized". What happens in reality, the same array gets resized or a new one it's created each time (the capacity limit ends)?

Thanks, Indeed ItIs

Upvotes: 0

Views: 346

Answers (4)

Spark-Beginner
Spark-Beginner

Reputation: 1364

Array in Java are fixed in size . you can not increase size of an array dynamically.

In the case of adding objects to ArrayList it check for ensureCapacity(), if it crosses limits then new array is created all the time.

Hope This will help you.

Upvotes: 0

Zavior
Zavior

Reputation: 6452

Internally, ArrayList uses the method ensureCapacity to make sure the underlying array is always large enough. From the openjdk source:

178     public void ensureCapacity(int minCapacity) {
179         modCount++;
180         int oldCapacity = elementData.length;
181         if (minCapacity > oldCapacity) {
182             Object oldData[] = elementData;
183             int newCapacity = (oldCapacity * 3)/2 + 1;
184             if (newCapacity < minCapacity)
185                 newCapacity = minCapacity;
186             // minCapacity is usually close to size, so this is a win:
187             elementData = Arrays.copyOf(elementData, newCapacity);
188         }
189     }

On the line 187 you can see it calls Arrays.copyOf, with a lenght specified. It creates a new array, and depending on the type of the array, it either pads with nulls, zeroes or so on.

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405755

You cannot resize an array in Java. A new one must be created.

Looking at the OpenJDK implementation, you can see that the add method calls a method named ensureCapacity that will "resize" the backing Object array if needed by making a copy.

public void  ensureCapacity(int minCapacity) {
    modCount++;
    int oldCapacity = elementData.length;
    if (minCapacity > oldCapacity) {
        Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;
        if (newCapacity < minCapacity)
            newCapacity = minCapacity;
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
}

Upvotes: 6

upog
upog

Reputation: 5531

While adding Objects to arrayList, if it exceeds the capacity then new array will be created as below

Arrays.copyOf(elementData, newCapacity)

Upvotes: 1

Related Questions