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.
Somewhere I saw a java.util.List defined as below. List<String> myList = new ArrayList<String>(0); Can
Share
The parameter decides the starting capacity of the
ArrayList.An
ArrayListallocates 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 yourArrayListto help Java.A starting size of
0probably indicates that the programmer thinks theArrayListwill 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
0as initial capacity. In the majority of cases, the default constructor works just fine.