Somewhere I saw a java.util.List
defined as below.List<String> myList = new ArrayList<String>(0);
Can anybody explain what the integer in parentheses does and how to use it? Thanks.
An ArrayList contains many elements. But in Java 8 it cannot store values. It can hold classes (like Integer) but not values (like int).
An ArrayList cannot store ints. To place ints in ArrayList, we must convert them to Integers. This can be done in the add() method on ArrayList.
ArrayList maintains the insertion order i.e order of the object in which they are inserted. HashSet is an unordered collection and doesn't maintain any order. ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
The parameter decides the starting capacity of the ArrayList
.
An ArrayList
allocates memory internally to hold a certain number of objects. When you add more elements too it, it has to allocate more memory and copy all the data to the new place, which takes some time. Therefor you can specify a guess on how many objects you are going to put in your ArrayList
to help Java.
A starting size of 0
probably indicates that the programmer thinks the ArrayList
will seldom be used, so there is no need to allocate memory for it to start with.
[EDIT]
To clarify, as @LuiggiMendoza and @emory say in the discussion, it is very hard to think of a scenario where it would make sense to use 0
as initial capacity. In the majority of cases, the default constructor works just fine.
To define an initial capacity of the ArrayList.
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