文章目录
  1. 1. 1.ArrayList:

1.ArrayList:

public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable

(1).实例域
private static final int DEFAULT_CAPACITY = 10;//默认容量是10
private static final Object[] EMPTY_ELEMENTDATA = {};//Shared empty array instance used for empty instances.

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
 * DEFAULT_CAPACITY when the first element is added.
 */
private transient Object[] elementData;//内部是使用数组实现的,

private int size;//The size of the ArrayList (the number of elements it contains).

(2).初始化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;//空数组进行初始化
}
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}

(3).添加:检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,不超出,按照数组的方式添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
   public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!()
elementData[size++] = e;
return true;
}

private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {

//发现目前数组是空数组,当前数组容量取为最少都是默认容量10,
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}

ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
modCount++;

// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}

private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容,*3/2+1
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}

(4).取出:先检查是否访问越界,再以数组形式访问

1
2
3
4
5
 public E get(int index) {
rangeCheck(index);

return elementData(index);
}

文章目录
  1. 1. 1.ArrayList: