This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details

A detailed analysis of the topic ArrayList

Think you know a lot about ArrayLists? Let’s look at the next piece of code

public static void main(String[] args) {
    List<String> list = new ArrayList<String>(10);
    list.add(2, "1");
    System.out.println(list.get(0));
}
Copy the code

Yeah, subscript is out of bounds

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
	at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:643)
	at java.util.ArrayList.add(ArrayList.java:455)
Copy the code

Array + List = Array + List = ArrayList = Array column

The data structure of ArrayList is implemented based on arrays, but the array is not like an array defined by us. It can be dynamically expanded and copied when inserting data under the management of ArrayList.

Second, source code analysis

private int size; /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); }}Copy the code

It is often more common to initialize an ArrayList with an empty constructor, where the length of the array is set the first time data is inserted.

When we already know how many elements to fill the ArrayList, such as 500 or 1000, to provide performance and reduce copy operations in the ArrayList, a preset length is initialized directly.

In addition, EMPTY_ELEMENTDATA is a defined empty object; private static final Object[] EMPTY_ELEMENTDATA = {}

01; The ordinary way
ArrayList<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
Copy the code
02; Inner class mode
ArrayList<String> list = new ArrayList<String>() \\{ add("aaa"); add("bbb"); add("ccc"); \ \};Copy the code
03; Arrays.asList
ArrayList<String> list = new ArrayList<String>(Arrays.asList("aaa", "bbb", "ccc"));
Copy the code

AsList is passed to the ArrayList constructor. See my article for a full explanation of this

Methods 4; Collections.ncopies

Collections.nCopies is the collection method used to generate how many copies of a given element. This is then used to initialize an ArrayList, as follows; This initializes a set of 10 zeros

    ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(10, 0));
Copy the code