我们常说的三种集合其实是三个接口,List和Set集合共同继承Collection这个父接口,Map集合是单独的一个接口,他们一共有六个实现类,List的实现类是LinkedList和ArrayList,Set的实现类有HashSet和TreeSet,Map的实现类有HashMap和TreeMap
ArrayList
UML图
- 继承:AbstractList
- 实现:List, RandomAccess, Cloneable, java.io.Serializable
实现了RandomAccess接口,RandomAccess是一个标志接口,表明实现这个这个接口的 List 集合是支持快速随机访问,官网还特意说明了,如果是实现了这个接口的 List,那么使用for循环的方式获取数据会优于用迭代器获取数据。
实现了Cloneable接口,表明它支持克隆。可以调用clone()进行浅拷贝。
实现了Serializable接口,表明它支持序列化。
实现了List接口,并且继承自AbstractList抽象类。
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{}
总结
1、ArrayList支持随机访问,底层是一个数组存放元素,所以在遍历ArrayList的时候,使用get()方法的效率要比使用迭代器的效率高,按照元素插入的顺序保持数据。
2、在ArrayList中经常使用的一个变量modCount,它是在ArrayList的父类AbstractList中定义的一个protected变量,该变量主要在多线程的环境下,如果使用迭代器进行删除或其他操作的时候,需要保证此刻只有该迭代器进行修改操作,一旦出现其他线程调用了修改modCount的值的方法,迭代器的方法中就会抛出异常。究其原因还是因为ArrayList是线程不安全的。
3、在ArrayList底层实现中,很多数组中元素的移动,都是通过本地方法System.arraycopy实现的,该方法是由native修饰的。
4、默认数组长度为10。
5、删除和移动元素性能较低,因为会导致整个集合元素的移动。
6、集合中的元素是可以重复的。
参考博客: https://blog.csdn.net/m0_37884977/article/details/80423075
全局变量
//默认容量为10
private static final int DEFAULT_CAPACITY = 10;
//空对象数组,用于在用户初始化代码的时候传入的容量为0时使用。
private static final Object[] EMPTY_ELEMENTDATA = {};
//默认的空数组,用于默认构造器中,赋值给顶层数组elementData。
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//存放数据的数组,不可序列化
transient Object[] elementData;
//数组的大小,即ArrayList中元素的个数
private int size;
//数组最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
构造方法
1. 带初始化容量initialCapacity的构造方法
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//new 一个等于initialCapacity大小长度的数组
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//将空的数组赋值给elementData
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
}
}
2.不带参的构造方法
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
3.带参数Collection的构造方法
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;
}
}
方法
1.trimToSize
说明:首先需要明确一个概念,ArrayList的size就是ArrayList的元素个数,length是ArrayList申请的内容空间长度。ArrayList每次都会预申请多一点空间,以便添加元素的时候不需要每次都进行扩容操作,例如我们的元素个数是10个,它申请的内存空间必定会大于10,即length>size,而这个方法就是把ArrayList的内存空间设置为size,去除没有用到的null值空间。这也就是我们为什么每次在获取数据长度是都是调用list.size()而不是list.length()。
源码解释:首先modCount是从类 java.util.AbstractList 继承的字段,这个字段主要是为了防止在多线程操作的情况下,List发生结构性的变化,什么意思呢?就是防止一个线程正在迭代,另外一个线程进行对List进行remove操作,这样当我们迭代到最后一个元素时,很明显此时List的最后一个元素为空,那么这时modCount就会告诉迭代器,让其抛出异常 ConcurrentModificationException。
如果没有这一个变量,那么系统肯定会报异常ArrayIndexOutOfBoundsException,这样的异常显然不是应该出现的(这些运行时错误都是使用者的逻辑错误导致的,我们的JDK那么高端,不会出现使用错误,我们只抛出使用者造成的错误,而这个错误是设计者应该考虑的),为了避免出现这样的异常,定义了检查。
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
2.size
源码解释:size记录了ArrayList的大小
public int size() { return size;}
3.isEmpty
源码解释:返回判断size==0
public boolean isEmpty() { return size == 0;}
4.indexOf(Object o)
源码解释:返回元素在ArrayList中的下标,首先判断o是否为空,因为ArrayList中元素可以为空,o为空,遍历ArrayList,返回elementData中等于null的元素下标。o不为空,遍历ArrayList,调用Object的equals方法获取相等的元素下标。如果遍历都不相等返回-1.
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;
}
5.contains(Object o)
源码解释:调用indexOf方法得到元素下标,如果下标大于等于0,则元素存在。
public boolean contains(Object o) { return indexOf(o) >= 0;}
6.lastIndexOf(Object o)
源码解释:和indexOf方法类似,不同的是反向遍历ArrayList。
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;
}
7.clone
源码解释:重写Object基类的clone方法,返回此ArrayList的浅克隆副本。
public Object clone() {
try {
//调用Obeject的clone方法得到一个ArrayList的副本
ArrayList<?> v = (ArrayList<?>) super.clone();
//调用Arrays的copyOf方法,将ArrayList的elementData数组赋值给副本的elementData数组
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
//返回副本v
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
8.toArray
源码解释:将ArrayList实例转化为数组,调用Arrays的copyOf方法
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
9.toArray(T[] a)
源码解释:如果a的长度小于ArrayList的长度,直接调用Arrays类的copyOf,返回一个比a数组长度要大的新数组,里面元素就是ArrayList里面的元素;如果a的长度比ArrayList的长度大,那么就调用System.arraycopy,将ArrayList的elementData数组赋值到a数组,然后把a数组的size位置赋值为空。
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;
}
10.rangeChek(int index)
源码解释:检测index下标是否越界。
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
11.get(index)
源码解释:获得指定下标的元素,首先调用rangeCheck检查下标是否越界,然后调用elementData方法放回ArrayList中index下标位置的元素。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
12.set(int index, E element)
源码解释:将index位置处的元素值替换为element,并返回该位置原先的值。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
13.ensureCapacityInternal(int minCapacity)
源码解释:判断ArrayList是否需要扩容。
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
14.calculateCapacity(Object[] elementData, int minCapacity)
源码解释:得到ArrayList最小容量,首先判断底层数组是否是DEFAULTCAPACITY_EMPTY_ELEMENTDATA(也就是说是不是使用了默认的构造器),是则将传入参数和默认容量进行比较,获取较大值。
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
15.ensureExplicitCapacity(int minCapacity)
源码解释:判断是否需要扩容,如果最小容量大于elementData的实际长度,则扩展数组容量。
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
16.grow(int minCapacity)
源码解释:扩展ArrayList的容量为原来的1.5倍。
private void grow(int minCapacity) {
// 获得原数组长度
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);
// 将elementData的数据赋值到新的内存空间
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;
}
17.add(E e)
源码解释:添加元素。调用ensureCapacityInternal方法,判断数组是否需要扩容,需要则将数组增大为原来的1.5倍,然后将元素添加到size下标处,并且数组实际大小加一(即size加1)。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
18.add(int index, E element)
源码解释:将元素插入到指定下标处。
public void add(int index, E element) {
//判断index下标是否越界,是则抛出数组下标越界异常。
rangeCheckForAdd(index);
//判断数组是否需要扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 将elementData从index位置开始,复制到elementData的index+1开始的连续空间,复制的长度为size-index
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
// 将elementData数组index下标处赋值为element
elementData[index] = element;
//数组实际大小加一
size++;
}
19.remove(int index)
源码解释:根据下标移除元素,并返回移除的元素值。
public E remove(int index) {
// 判断下标是否越界,是则跑出数组下标越界异常
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
// 获得要复制的数组的长度
int numMoved = size - index - 1;
if (numMoved > 0)
//将elementData从index+1位置开始,复制到elementData的index开始的连续空间,复制的长度为numMoved
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//将size位置的值赋值为空,并且size减1
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
20.remove(Object o)
源码解释:和indexOf类似,通过遍历ArrayLis从而删除对应元素,并返回是否成功。
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方法类似,删除元素。
private void fastRemove(int index) {
modCount++;
// 获得要复制的数组的长度
int numMoved = size - index - 1;
if (numMoved > 0)
//将elementData从index+1位置开始,复制到elementData的index开始的连续空间,复制的长度为numMoved
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//将size位置的值赋值为空,并且size减1
elementData[--size] = null; // clear to let GC do its work
}
21.clear()
源码解释:遍历ArrayList全部元素设置为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;
}
22.addAll(Collection<? extends E> c)
源码解释:将Collection c的全部元素添加到ArrayList中。
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
// 判断数组是否需要扩容,需要则扩展。
ensureCapacityInternal(size + numNew); // Increments modCount
// 将传进来的元素数组赋值到elementData中
System.arraycopy(a, 0, elementData, size, numNew);
// 数组大小加numNew
size += numNew;
return numNew != 0;
}
23.addAll(int index, Collection<? extends E> c)
源码解释:从第index位开始,将c全部拷贝到ArrayList。
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)
// 将elementData数组从index开始复制到elementData数组index + numNew开始的连续空间,复制长度为numMoved
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
// 将a数组从0开始复制到elementData数组index开始的连续空间,复制长度为numNew
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
24.removeAll(Collection<?> c)
源码解释:ArrayList移除c中的所有元素。
public boolean removeAll(Collection<?> c) {
// 判断c是不是为空,是则抛出异常
Objects.requireNonNull(c);
return batchRemove(c, false);
}
源码解释:批量删除元素。
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++)
// 如果c中不包含elementData[r]这个元素
if (c.contains(elementData[r]) == complement)
// 则直接将r位置的元素赋值给w位置的元素,w自增
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
// 防止抛出异常导致上面r的右移过程没完成
if (r != size) {
// 将r未右移完成的位置的元素赋值给w右边位置的元素
System.arraycopy(elementData, r,
elementData, w,
size - r);
//w的值增加size-r
w += size - r;
}
// 如果有被覆盖的元素,则将w后面的元素都设置为null
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
size = w;
modified = true;
}
}
return modified;
}
25.retainAll(Collection<?> c)
源码解释:和removeAll相反,仅保留c中的元素。
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
26.listIterator()
源码解释:返回一个ListIterator对象,ListItr是ArrayList的一个内部类,其实现了ListIterator接口。
public ListIterator<E> listIterator() {
return new ListItr(0);
}
27.listIterator(int index)
源码解释:返回一个从index开始的ListIterator对象。
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
28.iterator()
源码解释:返回一个Iterator对象,Itr是ArrayList的一个内部类,其实现了Iterator接口。
public Iterator<E> iterator() {
return new Itr();
}
29.subList(int fromIndex, int toIndex)
源码解释:返回的是父list的一个视图,从fromIndex(包含),到toIndex(不包含)。fromIndex=toIndex 表示子list为空。SubList是ArrayList的一个内部类,其继承了AbstractList类,实现了RandomAccess接口。
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
内部类
Itr
实现了Iterator接口,实现或重写了Iterator接口中的hasNext、next、remove、forEachRemaining方法。
Itr中的字段和方法:
int cursor; // 游标,指向下一个将要返回的元素下标
int lastRet = -1; // 上一个元素(当前元素)位置,上一个元素是相对与cursor来说的,cursor指向下一个元素,lastRet其实就是当前元素
int expectedModCount = modCount; // 在ArrayList中经常看到modCount,判断是否有多个线程访问修改
// 判断cursor != size是否相等,可以用来判断是否还有下一个元素
public boolean hasNext() {
return cursor != size;
}
// 返回下一元素(cursor指向的元素)
npublic E next() {
// 检查modCount和expectedModCount是否相等,不相等则抛出异常
checkForComodification();
int i = cursor;
// 下一个元素下标越界,抛异常
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
// 光标+1
cursor = i + 1;
// 放回下一个元素,lastRet此时指向的上一元素为,返回的元素
return (E) elementData[lastRet = i];
}
// 删除上一元素(lastRet指向的元素),删除当前元素后,只能在让iterator指向下一个元素iterator.next(),才能继续删除,否则抛出异常
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
// 删除lastRet指向的元素
ArrayList.this.remove(lastRet);
// 光标指向的位置向前以为,即lastRet的位置
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 支持lambda表达是遍历,不适用于删除元素,此方法不调用next,并且最后才更改lastRet和cursor
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer); // consumer为空抛异常
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
// 如果不等表示ArrayList被另一个线程修改了
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
ListItr
继承Itr,实现了ListIterator接口,重写了hasPrevious、nextIndex、previousIndex、previous、set、add方法,可以看出ListIterator在Iterator的基础上又增加了添加对象,修改对象,逆向遍历等方法,这些都是iterator不能实现的。
// 获取前一个元素
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
// 修改当前元素(lastRet)的值
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 添加一个元素到cursor光标处,并且lastRet赋值为-1
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
SubList
继承AbstractList抽象类,实现RandomAccess接口。这个类中的大部分的方法都是在调用ArrayList的方法:ArrayList.this.elementData(offset + index)。且这个类的所有方法,都会调用:checkForComodification(),主要是判断ArrayList类中的modCount与SubList类中的modCount是否相等。
Sublist类维护的数据域,其实就是外部类的数据域,对Sublist类的数据域进行修改,同时也修改了其外部的ArrayList类的数据域。这时可能就会出现问题,同时有两个对象在操作同一个数据域,存在线程安全的问题。如果一个线程在迭代ArrayList对象,另外一个线程在修改Sublist对象,就会抛出异常。
private final AbstractList<E> parent; // ArrayList对象
private final int parentOffset; // 从parentOffset下标处开始,包含parentOffset
private final int offset; // 表示SubList子序列开始下标
int size; // 子序列大小
// subList传参中offset为0
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
modCount父类变量的作用
modCount是AbstractList基类中的变量,记录了ArrayList结构性变化的次数。在ArrayList的所有涉及结构变化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。这些方法每调用一次,modCount的值就加1。
在Itr内部类和ListItr内部类中,每个方法都调用了checkForComodification()。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
fset; // 表示SubList子序列开始下标
int size; // 子序列大小
// subList传参中offset为0
SubList(AbstractList parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
## modCount父类变量的作用
modCount是AbstractList基类中的变量,记录了ArrayList结构性变化的次数。在ArrayList的所有涉及结构变化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。这些方法每调用一次,modCount的值就加1。
在Itr内部类和ListItr内部类中,每个方法都调用了checkForComodification()。
```java
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
现在对modCount和expectedModCount的作用应该非常清楚了。在对一个集合对象进行跌代操作的同时,并不限制对集合对象的元素进行操 作,这些操作包括一些可能引起跌代错误的add()或remove()等危险操作。在AbstractList中,使用了一个简单的机制来规避这些风险。 这就是modCount和expectedModCount的作用所在