一.概述
1.ArrayList是可以动态增长和缩减的索引序列,它是基于数组实现的list类
2.该类封装了一个动态再分配的Object[]数组,每个ArrayList的实现类都有一个capacity属性,表示它所封装的Object[]数组的容量.当arrayList添加元素时,该属性会自动增加.同时在ArrayList大量添加元素时,可以使用ensureCapacity一次性增加容量,可以减少扩容的次数来提高性能.
3.ArrayList是线程不安全的.
4.ArrayList继承结构
思考:
1.为什么要继承abstractList这些抽象类?
继承抽象类中的通用实现方法.减少重复代码.
2.为什么实现RandomAccess接口?
这个是一个标记性接口,通过查看api文档,它的作用就是用来快速随机存取,有关效率的问题,在实现了该接口的话,那么使用普通的for循环来遍历,性能更高,例如arrayList。而没有实现该接口的话,使用Iterator来迭代,这样性能更高,例如linkedList。所以这个标记性只是为了让我们知道我们用什么样的方式去获取数据性能更好。
二.类中的属性
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
/**
* 默认初始容量
*/
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.
共享的空数组实例,用于默认大小的空实例。我们将其与EMPTY_ELEMENTDATA区别开来,
以了解添加第一个元素时需要充气多少。
*/
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.
存储ArrayList元素的数组缓冲区。ArrayList的容量是此数组缓冲区的长度。
添加第一个元素时,任何具有elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
的空ArrayList都将扩展为DEFAULT_CAPACITY。
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* The size of the ArrayList (the number of elements it contains).
* 数组的大小(列表包含元素的数量)
*/
private int size;
/**
* 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;
三.构造函数
1.无参构造函数
构造一个初始容量为10的空集合
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
2.指定容量的构造函数
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);
}
}
3.构造包含指定集合的列表 先转化为数组,再复制元素
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;
}
}
例:
Set<Integer> intSet = new HashSet<>();
intSet.add(20);
ArrayList<Integer> strList = new ArrayList<Integer>(intSet);
四.核心方法
1.添加add
(1)add(E e)
/**
* Appends the specified element to the end of this list.
* 在列表末尾添加元素
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
//确保内部容量,此处size为当前列表大小
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//如果当前列表元素为空
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
最小容量为10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//此时如果列表元素为空 则minCapacity=10 如果不为空原来有数据则为原有大小加1
ensureExplicitCapacity(minCapacity);
}
确保容量
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
//如果需要的最小容量大于元素本身容量则扩充容量
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
重点:这里是扩容的核心 如果原列表为空则扩容后新的列表为10,如果不为空,则扩展1.5倍.例如8变成12
private void grow(int minCapacity) {
// overflow-conscious code
//1.原列表为空 2原列表有元素假设为8
int oldCapacity = elementData.length;
//如果原列表为空 则newCapacity=0+0=0
//如果假设原列表有元素 则newCapacity为旧容量的1.5倍
//例如:原有8个元素 newCapacity=8+8/2=12;
int newCapacity = oldCapacity + (oldCapacity >> 1);
//这里相当于原list为空的情况,0-10<0 则扩充初始容量为10
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;
}
最终回到elementData[size++] = e;将新的值赋值到list最后.
(2)add(int index,E e)
public void add(int index, E element) {
//检查添加范围,如果大于列表大小,或者小于0 则抛出IndexOutOfBoundsException异常
rangeCheckForAdd(index);
//和尾部添加一样 扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
//将插入位置起所有元素向后移动一位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
2删除remove clear
(1)remove(int index) 根据下标删除
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);
//将末尾设置为null 让gc(垃圾回收机制)更快的回收它
elementData[--size] = null; // clear to let GC do its work
//返回旧值
return oldValue;
}
(2)remove(Object o) 根据具体元素删除列表中的该元素,分为删除null元素和非空元素
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和remove(index)基本一致.只是去掉了范围检查和返回值
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
}
(3)clear()清除所有元素 将元素全部设置为null 让GC垃圾回收
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
(4)removeAll(Collection<?> c)
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
//批量删除
return batchRemove(c, false);
}
用于两个方法,一个removeAll():它只清除指定集合中的元素,retainAll()用来测试两个集合是否有交集。
//用于两处地方,如果complement为false,则用于removeAll如果为true,
//则给retainAll()用retainAll()是用来检测两个集合是否有交集的。
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.
//当有异常出现时,循环停止,此时r不等于size.但是依旧会吧后面的元素直接
//加到新的列表中
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
//如果w不等于原始大小 则证明有删除元素
if (w != size) {
// clear to let GC do its work
//将新列表后多的元素设置null gc收集
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
3.Set(int index, E element)设置指定位置元素
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}