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")
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With