0%

Java ArrayList

阅读Java8的ArrayList源码,写下了自己的一些笔记

ArrayList继承了AbstractList类并实现了List、RandomAccess、Cloneable、java.io.Serializable接口

相关常量

  • DEFAULT_CAPACITY=10默认的容量初始值
  • DEFAULTCAPACITY_EMPTY_ELEMENTDATA默认的空Object数组
  • EMPTY_ELEMENTDATA空Object数组
  • MAX_ARRAY_SIZE最大数组容量,为Integer.MAX_VALUE - 8

相关变量

  • private intArrayList的容量
  • transient Object[]存储数据的数组,无法被序列化
  • transient int modCount用于记录当前ArrayList被修改的次数

三种构造函数

1
2
3
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

将数组指向静态变量空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA,避免内存中存在大量的空数组,节省空间

1
2
3
4
5
6
7
8
9
10
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);
}
}

构造函数,当大于0的时候new一个大小为initialCapacity的数组,等于0则将数组指向静态变量空数组EMPTY_ELEMENTDATA,小于0抛出异常

1
2
3
4
5
6
7
8
9
10
11
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}

调用容器的toArray方法,传入容量原数组的容量到size
由于部分toArray方法返回的不是Object[],因此如果类型不为 Object[]时,复制原容器中的元素到elementData中,保证elementData是 Object[]类型的
当size为0时,数组指向静态变量空数组EMPTY_ELEMENTDATA

相关方法

size

1
2
3
public int size() {
return size;
}

显而易见

isEmpty

1
2
3
public boolean isEmpty() {
return size == 0;
}

显而易见

contains

1
2
3
public boolean contains(Object o) {
return indexOf(o) >= 0;
}

调用indexOf方法,当返回值>=0返回true

indexOf

1
2
3
4
5
6
7
8
9
10
11
12
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}

在判断是否包含时,调用的是类的equals方法,返回的是索引位置,如果不存在返回-1
ArrayList可以包含null

lastIndexOf

1
2
3
4
5
6
7
8
9
10
11
12
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}

与indexOf基本相同,不过是倒着来的

get

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

return elementData(index);
}

调用范围检测,避免数组越界,返回elementData[index]的值
rangeCheck只检查了上界,下界由编译器自动检查

rangeCheck

1
2
3
4
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

检查数组是否越界,如果越界抛出异常
rangeCheck只检查了上界,下界由编译器自动检查

elementData

1
2
3
E elementData(int index) {
return (E) elementData[index];
}

返回数组值

add

1
2
3
4
5
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

每次添加元素,都会保证数组容量足够,调用ensureCapacityInternal方法
在数组下一个位置,放置元素
返回true

1
2
3
4
5
6
7
8
9
public void add(int index, E element) {
rangeCheckForAdd(index);

ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}

重载了一个add
检查数组是否越界
检查容量,调用ensureCapacityInternal方法
数组复制
对应的位置赋值
数组容量++
注意此处返回的不是true,此方法是void返回值

rangeCheckForAdd

1
2
3
4
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

相较于之前的rangeCheck,这里多了一个小于0的判断,我的理解是,避免了在index不合法的情况下,调用相关容量扩充方法或者移动方法,减少不必要的动作

ensureCapacityInternal

1
2
3
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

调用相关方法,保证容量大小满足条件

calculateCapacity

1
2
3
4
5
6
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}

该函数返回elementData应该的容量
判断,如果elementData是通过无参构造函数构造出来的DEFAULTCAPACITY_EMPTY_ELEMENTDATA的话,返回DEFAULT_CAPACITY(10)和最小数组大小中的最大值
如果不是,则直接返回minCapacity

ensureExplicitCapacity

1
2
3
4
5
6
7
private void ensureExplicitCapacity(int minCapacity) {
modCount++;

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

增加修改次数
判断,避免溢出成为负数
如果最小要求容量大于当前数组的容量,调用grow

grow

1
2
3
4
5
6
7
8
9
10
11
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 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);
}

扩容,每次扩容的大小变为原来的1.5倍
如果扩容不满足容量条件,新数组的容量就置为满足要求的最小容量
如果新数组容量大小大于MAX_ARRAY_SIZE,则调用hugeCapacity函数,获得新数组的容量

hugeCapacity

1
2
3
4
5
6
7
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}

如果满足要求的最小容量小于零,即发生溢出,则抛出异常
如果最小要求容量大于MAX_ARRAY_SIZE,则返回Integer.MAX_VALUE,否则返回最小要求容量

set

1
2
3
4
5
6
7
public E set(int index, E element) {
rangeCheck(index);

E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

检查边界,设置新的值,返回旧的值

remove

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public E remove(int index) {
rangeCheck(index);

modCount++;
E oldValue = elementData(index);

int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work

return oldValue;
}

检查边界,modCount++,获得旧的值,该索引后的数组向前移动一位,并将最后一位的引用设置为null,返回旧的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}

先遍历寻找是否相同,再调用fastRemove方法,如果成功删除,返回true,反之返回false
较之另一个重载,因为没有用到index,因此没有检查边界

fastRemove

1
2
3
4
5
6
7
8
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}

和之前的remove方法基本一致

clear

1
2
3
4
5
6
7
8
9
public void clear() {
modCount++;

// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;

size = 0;
}

modCount++,将所有位的置为null,并将size置为0

addAll

1
2
3
4
5
6
7
8
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}

调用toArray方法,调用的ensureCapacityInternal方法,并进行数组复制,调整size大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);

Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount

int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);

System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}

基本相同,多了一个边界检查

removeRange

1
2
3
4
5
6
7
8
9
10
11
12
13
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);

// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}

删除范围内的值

removeAll

1
2
3
4
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}

调用requireNonNull方法,如果是null则抛出NullPointerException异常,调用batchRemove方法,移除那些在c中的元素

retainAll

1
2
3
4
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}

调用requireNonNull方法,如果是null则抛出NullPointerException异常,调用batchRemove方法,移除那些不在c中的元素

batchRemove

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
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}

循环检查,判断是否满足条件(remove/retain),arraycopy复制数组,并将后面的元素置为null,等待gc
arraycopy实现的是浅拷贝

参考资料

  • JDK1.8源码