ArrayList 简介:
ArrayList 相当于一个动态数组, 他的容量可以动态增加。
下图是ArrayList 的继承实现关系。
需要注意的一点是,ArrayList 中的操作不是线程安全的。
基本元素:
ArrayList 属性主要就是当前数组的长度 size。 以及存放数组的对象 elementData。 还有一个经常用到的属性就是从AbstratList继承过来的modCount 属性, 代表 ArrayList 集合的修改次数。
// 默认初始的容量大小为 10
private static final int DEFAULT_CAPACITY = 10;
// 指定容量为 0 时, 返回这个空数组。
private static final Object[] EMPTY_ELEMENTDATA = {};
// 默认的时候, 就是没有指定数组的大小, 返回这个空数组, 和之后的元素扩容有关系。
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 当前数据对象存放的地方。
transient Object[] elementData; // non-private to simplify nested class access
// 元素个数。
private int size;
构造函数:
无参构造函数:
如果不传入参数,使用默认无参构造。
需要注意的是:
这个时候创建的 ArrayList 对象中 size 是 0,elementDate 的长度也是0,也就是说集合里面还没有元素, 当第一次 add 的时候, size 变成了 1, elementData 将会变成默认长度 10.
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
带 int 类型的构造参数
如果传入了参数, 就代表指定了 ArrayList 的初始化长度。
-
参数 > 0 , 直接new 一个出来。
-
参数 = 0 ,返回指定长度为 0 的对象。为了区别默认情况长度为 0.
-
参数 < 0 ,异常处理。
// 有参构造,指定元素个数
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);
}
}
批量构造函数
-
将集合变成数组
-
更新集合 size, 如果size 不为 0, 把传入的集合复制过来
-
如果siez = 0, 返回空对象
// 从原有的集合中创建一个新的数组。
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;
}
}
常用方法:
get(int index)
-
传入一个下标
-
判断下标是否越界
-
返回下标的元素
public E get(int index) {
// 越界检查
rangeCheck(index);
// 取值
return elementData(index);
}
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
// 判断是不是越界
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// Positional Access Operations
// 取值
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
set(int index, E element)
-
传入下标和元素
-
判断下标是否越界
-
带到旧元素, 下标位置换成新元素
-
返回就元素
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
private void rangeCheck(int index) {
// 判断是不是越界
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// Positional Access Operations
// 取值
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
add(E e)
public boolean add(E e) {
// 判断容量是不是够, 在原有的 size + 1
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
// 如果是无参构造,那就 默认容量 和 最小容量 取 max。
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
// 否则返回 最小容量。
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 如果 最小容量 大于 已有容量, 那么就扩容
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 新容量为旧容量的 1.5 倍
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
add 总结:
-
空间检查,如果有需要进行扩容
-
插入元素
扩容总结:
-
进行空间检查,决定是否进行扩容,以及确定最少需要的容量
-
如果确定扩容,就执行grow(int minCapacity),minCapacity为最少需要的容量
-
第一次扩容,逻辑为newCapacity = oldCapacity + (oldCapacity >> 1);即在原有的容量基础上增加一半。
-
第一次扩容后,如果容量还是小于minCapacity,就将容量扩充为minCapacity。
-
对扩容后的容量进行判断,如果大于允许的最大容量MAX_ARRAY_SIZE,则将容量再次调整为MAX_ARRAY_SIZE。至此扩容操作结束。
add(int index, E element)
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++;
}
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
remove(int index)
public E remove(int index) {
// 判断 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;
}
-
检查索引是否越界。如果参数指定索引index>=size,抛出一个越界异常
-
将索引大于index的元素左移一位(左移后,该删除的元素就被覆盖了,相当于被删除了)。
-
将索引为size-1处的元素置为null(为了让GC起作用)。
remove(Object o)
删除指定元素
-
判断给定的元素是不是 null
-
如果给定的元素是 null , 从前到后遍历一遍找到null的位置
-
如果给定的元素不是 null, 也从前到后遍历一遍, 找到要删除元素的位置。
-
找到位置index之后, 执行 fastRemove,
-
把index之后的元素全部往前移动一个位置。
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;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
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
}
indexOf(Object o)
这个是 O(n) 的复杂度,就是遍历一遍, 然后每个位置匹配一下,判断是不是一样。
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
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;
}
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;
}
clear()
从前到后每个位置都变成 null, 然后 size 变成 0.
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}