ArrayList
- A constructor
// There are parameters
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
// Initializing less than zero throws exceptions at run time
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); }}/** * Constructs an empty list with an initial capacity of ten */ Constructs an empty list with an initial capacity of ten
public ArrayList(a) {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
Copy the code
test
@Test
public void arrayListTest(a) {
// No arguments
List<Integer> list = new ArrayList<>();
// The initial capacity is 0
System.out.println(getArrayListCapacity(list));/ / 0
// Add an element and the initial capacity becomes 10
list.add(1);
System.out.println(getArrayListCapacity(list));/ / 10
// Parameterized constructs start with 0
List<Integer> list1 = new ArrayList<>(0);
// The initial capacity is 0
System.out.println(getArrayListCapacity(list1));/ / 0
// Add an element and the initial capacity becomes 1
list1.add(1);
System.out.println(getArrayListCapacity(list1));/ / 1
}
public int getArrayListCapacity(List<Integer> arrayList) {
Class<ArrayList> arrayListClass = ArrayList.class;
try {
Field field = arrayListClass.getDeclaredField("elementData");
field.setAccessible(true);
Object[] objects = (Object[]) field.get(arrayList);
return objects.length;
} catch (NoSuchFieldException e) {
return -1;
} catch (IllegalAccessException e) {
e.printStackTrace();
return -1; }}Copy the code
- summary
An ArrayList can be expanded automatically, either without passing an initial capacity or if the initial capacity is 0, an empty array will be initialized, but if you add elements, it will be expanded automatically. Therefore, when creating an ArrayList, it is necessary to give the initial capacity
The capacity expansion is 1.5 times the original capacity.
In capacity expansion, create a list and copy the original data.