Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between implicit and explicit ArrayList size declarations?

what is the difference between the following declarations:

List list1 = new ArrayList();

List list2 = new ArrayList(10);

By default is allocates it with 10. But is there any difference? Can I add an 11th element to list2 by list2.add("something")?

like image 806
v0ld3m0rt Avatar asked Aug 10 '16 05:08

v0ld3m0rt


People also ask

What is difference between capacity and size of ArrayList?

An ArrayList object has a capacity and a size. The capacity is the total number of cells. The size is the number of cells that have data in them. Cells 0 up through size-1 have data in them.

What is default size of an ArrayList?

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.

How does the size of ArrayList grow dynamically?

The grow method in the ArrayList class gives the new size array. In Java 8 and later The new capacity is calculated which is 50% more than the old capacity and the array is increased by that capacity. It uses Arrays.

Can you initialize an ArrayList with size?

ArrayList inherits AbstractList class and implements List interface. ArrayList is initialized by a size, however the size can increase if collection grows or shrink if objects are removed from the collection.


1 Answers

Here is the source code for you for first example

public  ArrayList() {
    this(10);
 }

So there is no difference. Since the initial capacity is 10, no matter you pass 10 or not, it gets initialised with capacity 10.

Can I add 11th element in the list2 by list2.add("something")?

Ofcourse, initial capacity is not final capacity. So as you keep on adding more than 10, the size of the list keeps increasing.

If you want to have a fixed size container, use Arrays.asList (or, for primitive arrays, the asList methods in Guava) and also consider java.util.Collections.unmodifiableList()

Worth reading about this change in Java 8 : In Java 8, why is the default capacity of ArrayList now zero?

In short, providing initial capacity wont really change anything interms of size.

like image 106
Suresh Atta Avatar answered Oct 21 '22 03:10

Suresh Atta