Default Size ArrayList

Looking through some piece of code, I noticed one strange initialization of ArrayList:

... = new ArrayList<..>(0);

I opened up JavaSE 7 sources and saw that the elementData internal attribute is initialized to an empty array constant - {}. When we pass the container to the constructor ArrayList, we do almost the same thing - new Object[0]. So my question is: is there a difference between new ArrayList(0)and new ArrayList()? Shouldn't the ArrayListdefault capacity size be set to something like 10?

Thanks everyone for the answers.

+4
source share
4 answers

An ArrayListhas an internal array for storing list items.

Java 7 8:

new ArrayList<>(0), ArrayList 0.

new ArrayList<>(), ArrayList 0 .

EDIT:

Javadoc ArrayList , , .

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    super();
    this.elementData = EMPTY_DEFAULTCAPACITY_EMPTY_ELEMENTDATA; // = static, empty
}

10 , :

public void ensureCapacity(int minCapacity) {
    int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
        // any size if not default element table
        ? 0
        // larger than default for default empty table. It already
        // supposed to be at default size.
        : DEFAULT_CAPACITY; // = 10

    if (minCapacity > minExpand) {
        ensureExplicitCapacity(minCapacity);
    }
}
+2

:

.

. , ;

Array Length Example = 2

Arraylist:

:

List<String> list = new ArrayList<>();
System.out.println(l.size());

: 0

?

, , ArrayList, :

private static final Object[] EMPTY_ELEMENTDATA = {}; 

, , 0 (). , 0.

list state when using the default constructor (id of elementData = 27)

, 1, 10 (); (id of elementData = 30)

private static final int DEFAULT_CAPACITY = 10

List state after adding one item  (id of elementData = 30)

ArrayList, API java : API Java: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList%28%29

public ArrayList()

Constructs an empty list with an initial capacity of ten.

, ( 0) . ( 10)

, . ? add (E element) O (1), ( ), O (n) ( ), , , ( 1,5 ), . , .

, 0 . , , .

, ArrayList :

Core Java 2:

ArrayList < 'Employee > (100)// 100

- , Employee [100]// 100

. 100 , 100 , . 100 100 (, , 100, ); , build, .

+3

ArrayList 2 . = 10:

ArrayList() {this(10);}

ArrayList(capacity)

? , arraylist. , , , , ( ) +, , ( ). . , . , , .

. Arraylist (0) 0, 1- , .

+1

ArrayList () will create a list of 10 (by default) after adding the first item. However, ArrayList (0) will maintain a small capacity - it will be 1 after adding the first element, 2 after the second adding, etc.

+1
source

Source: https://habr.com/ru/post/1627780/


All Articles