简体   繁体   中英

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.

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.

定义ArrayList的初始容量。

It is to define an initial capacity of the ArrayList .

You are not obliged to pass a size parameter if you want because there is a constructor that has no arguments as well.

Whenever you add an additional element, and if the list size doesn't permit for addition, the List class will create another List in the Heap with a larger size and will copy the content of the old array to it with the additional element, deleting the old array .

The capacity in the initial instantiation is there to create the exact size of the List which helps in not allocating additional blocks of memory by creating new Lists , deleting the old ones and copying the contents at run time, where it helps in performance.

它指定列表的容量

Don't confuse with the size of the array list and its capacity :

  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

When you call new ArrayList<String>(0) , you are setting the list's initial capacity , not its size. In other words, when constructed in this manner, the array list starts its life empty.

When used as

List<String> strList = new ArrayList<String>(5);

It Constructs an empty list with the specified initial capacity.

By default when nothing is specified.

List<String> strList = new ArrayList<String>;

an empty list with an initial capacity of ten is constructed.

Read Here

Do not misundetstand this as size of the ArrayList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM