Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an Integer within the parentheses of an ArrayList

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.

like image 640
prageeth Avatar asked Jul 13 '12 04:07

prageeth


People also ask

Why does ArrayList use Integer and not int?

An ArrayList contains many elements. But in Java 8 it cannot store values. It can hold classes (like Integer) but not values (like int).

Can an ArrayList have integers?

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.

Why is an ArrayList ordered?

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.


2 Answers

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.

like image 178
Keppil Avatar answered Oct 19 '22 05:10

Keppil


To define an initial capacity of the ArrayList.

like image 20
Guanlun Avatar answered Oct 19 '22 06:10

Guanlun