Java源码版本
Java8
ArrayList特点
- 实质维护了一个Object动态数组;
- 查询速度快,其中插入和移除元素时较慢。因为插入删除时,需要整体移动元素的位置。
相关基础知识
- transient关键字
- 当对象被序列化时,transient阻止实例中那些用此关键字声明的变量持久化;
- 当对象被反序列化时,这样的实例变量值不会被持久化和恢复。
- System.arraycopy()与Arrays.copyOf()方法区别?
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
src 源数组
srcPos 源数组起始位置
dest 目标数组
destPos 目标数组起始位置
length 复制长度
- Arrays.copyOf()最终也是调用了System.arraycopy()实现。
- Arrays.copyOf()对待不同数据类型有不同的重载方法,在其内部新建一个数组,然后使用System.arraycopy()去copy至新数组,返回新的数组。
- System.arraycopy()又是native方法。
ArrayList类定义
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
- 继承AbstractList<E>可以看出支持泛型。
- 继承了AbstractList,实现List<E>接口,AbstractList<E>本身也实现了List<E>接口。
- 实现RandomAccess,接口中没有定义内容,JDK文档中说明实现该接口,表明其支持快速随机访问,具体怎么个快速法,后续再查资料。
- 实现Cloneable接口,接口中没有定义内容,ArrayList中clone方法,是Object类中被protected修饰的方法,实现该接口后,需要重写该方法为public,为浅拷贝。
- 实现java.io.Serializable接口,支持序列化,能够序列化输出未经transient修饰的变量。
ArrayList类属性
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
- ArrayList实质是维护一个动态数组,数组名为elementData;
- 数组中元素个数用size表示。当初始化ArrayList时,默认容量为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,为空。当调用add方法,添加元素时,elementData容量初始化为DEFAULT_CAPACITY,为10。
- 使用transient修饰elementData,由于ArrayList实现了Serializable接口,可以被序列化,也就是ArrayList属性,可以用于网络传输,存储至磁盘持久化。当有些属性不愿意被序列化时,就可以使用transient修饰。
ArrayList类构造方法
三个构造方法
/**
* 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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
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;
}
}
- public ArrayList(int initialCapacity);
带参数构造方法,传入初始数组容量值,构造指定大小的elementData数组; - public ArrayList();
无参,此时elementData默认为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,容量大小为0 - public ArrayList(Collection<? extends E> c);
传入一个集合初始化ArrayList,然后将集合C转换为Array再赋值给elementData
ArrayList核心方法
- trimToSize()
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
- 调整当前elementData的容量,为实际当前已存入数据的长度,即size大小。能够减小elementData占用的内存。
- ensureCapacity()
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
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 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* Increases the capacity to ensure that it can hold at least the
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
- public void ensureCapacity(int minCapacity){};
增长elementData的容量,当容量不够时,扩充容量,从int newCapacity = oldCapacity + (oldCapacity >> 1);中可以看出每次扩充1.5倍。 - 若传入的最小扩容后容量minCapacity大于增加1.5倍后的容量,那么直接扩充至minCapacity,而不是1.5倍。
- size()
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
- 这两个方法,都是通过属性size,存入数据的长度去返回或判断。
- contains()、indexOf()、lastIndexOf()
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;
}
- 以上三个为集合常规方法,判断ArrayList中,是否存在某个元素,存在返回该值下标,不存在返回-1。lastIndexOf(Object o),反向遍历数组,判断。当待判断元素不为空时,这里采用的是equals()方法,去判断。
- public boolean contains(Object o) {};
该方法用来判断数组中是否存在该值,直接去调用indexOf(Object o)方法,若返回下标不为-1,则说明该ArrayList中存在该值。
- clone()方法
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
- 克隆方法,调用父类clone()方法,使用Arrays.copyOf(),拷贝。
- toArray()
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
- 拷贝elementData中所有元素,并返回至一个新的数组。
- toArray(T[] a)
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
- 若传入数组长度小于elementData长度,则返回一个新数组,使用其数据类型,但是为elementData中内容。
- 若传入数组长度大于elementData长度,返回复制的elementData,同时使返回数组的第size位,为null。
- 若传入数据数组长度等于elementData长度,则返回elementData数组的复制。
- elementData(int index)
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
- 返回elementData中指定下标的元素。
- get() set()方法
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
- 获得ArrayList中指定下标的值,先对下标值进行判断,是否小于elementData的长度size,若超出范围,抛出异常。然后调用elementData()方法,返回指定下标元素。
- public E set(int index, E element) {};
该方法为替换掉ArrayList中指定下标元素的值。
- add(E e)
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
- 该方法为向elementData尾部添加元素,先查看数组容量,不够,则扩容至1.5倍。
- 使用ArrayList()构造方法初始化时,默认为空,在添加第一个元素后,才会其中分配容量。
- public void 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++;
}
- 在指定位置中插入一个元素,同样显示查看elementData中容量是否足够,先将elementData中index以后的元素,整体向右移动一位,然后在下标为index的位置处插入新的元素。由于这里的整体移动,导致ArrayList(),增加元素慢。
- remove(int index)、remove(Object o)
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;
}
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;
}
- 第一种remove(int index),根据元素下标值,进行移除,若移除位于最尾端,直接对最后一个元素赋值为null,不用移动元素;若位于中间部分,则需要先进行元素移动,再 将尾部元素赋值为null,返回被移除的元素。
- 第二种remove(Object o),移除对象元素,通过遍历是否存在该对象,若存在则调用fastRemove(index)方法,移除,而不是调用remove(index)方法,这是因为,fastRemove()里不用去调用rangeCheck(index)方法判断边界,移除成功,返回true;未查找到返回false。
- 在调用这些方法时,使用了System.arraycopy()方法,来将其它数据进行复制移动。因此,ArrayList类的删除操作会慢。
- clear()
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
- 清空ArrayList,移除所有元素,所有元素赋为null,size设置为0。留给GC处理。 当clear()后,是不是也可以调用调整elementData的length等于size。
- addAll(Collection<? extends E> c),addAll(int index, Collection<? extends E> c)
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;
}
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;
}
- public boolean addAll(Collection<? extends E> c){}
该方法将集合c数据,添加至elementData尾部。 - public boolean addAll(int index, Collection<? extends E> c){}
该方法将集合c插入到指定下标处,若插入下标等于size,则直接添加至尾部。否则,将index后的numNew个数据右移一位,然后再把集合C插入到index处。
- removeAll(Collection<?> c),retainAll(Collection<?> c)
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
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;
}
- public boolean removeAll(Collection<?> c) {}
移除elementData中与指定集合C中相同的数据。核心通过调用batchRemove(Collection<?> c, boolean complement)方法,该方法通过传递complement来判断是保留还是删除,true为保留,false为删除。 - public boolean retainAll(Collection<?> c) {}
保留elementData中与指定集合C中相同的数据,移除其它数据。
总结
实质上ArrayList就是一个稍微复杂点的动态数组,能够动态增加数组容量。 在每次添加元素的时候,都会先调用ensureExplicitCapacity()方法,去判断elementData中容量,当容量不够时,调用grow()方法,去增大容量,首先通过 oldCapacity + (oldCapacity >> 1) 增大为elementData中原有容量的1.5倍,若容量仍然不够,则直接扩充至请求的容量。这样可以保证elementData每次都接近实际size的大小。扩容后,会调用 Arrays.copyOf()方法,将元素移动至新的数组中,所以每次使用ArrayList添加元素时,因此添加元素时会慢一些;同时在remove()时,也会去移动元素。Arrays.copyOf()实现是调用System.arraycopy()方法。因此,当容量确定时,使用ArrayList会比较高效。
说明
只是个人对Java的一点点总结,存在不准确或者错误地方,欢迎给予指出。