一、结构关系
二、重要源码分析
①数据结构
transient Object[] elementData;
意味着ArrayList里面的对象都是用不可序列化对象数组存储的,因为数组里面存的是数组的引用,而引用默认占4字节,由于这一特点,随机查询快。
②构造函数
private static final Object[] EMPTY_ELEMENTDATA = {}; //空数组实例
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
默认构造函数,共享的空数组实例 DEFAULTCAPACITY_EMPTY_ELEMENTDATA
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
// 对initialCapacity 进行判断
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) { initialCapacity判断
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
// 创建一个包含collection的ArrayList
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;
}
}
三、扩容机制
elementData 存储对象的数组引用
size ArrrayList里面元素的个数
public boolean add(E e) {
对当前元素个数容量+1,确保elementData所指向的数组对象容量足够
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) {
如果elementData指向空对象数组,容量取DEFAULT_CAPACITY 10,如果不指向空,说明不是第一次扩容,minCapacity大于 10
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
确保明确的容量
private void ensureExplicitCapacity(int minCapacity) {
modCount++; 修改次数+1
// overflow-conscious code
如果添加数据之后的容量大于 elementData所指向数组对象的容量,则要进行扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
增长容量
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
每次扩容都扩容1.5倍
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;
}
流程:①第一次添加,size=0,因为初始化elementData指向空数组,第一次扩容容量为10,此时modcount+1, grow(10), 此时执行Arrays.copyOf() 方法进行数组复制.
String的hash默认为0
②当数组中长度已为10,数组长度增加到 10+10>>1 =15,然后执行Arrays.copyOf() ,最后进行elementData[size++] = e 赋值,返回true
四、remove方法
ArrayList本身有两个remove方法
按指定索引位置删除
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 赋值null,gc回收
return oldValue;
}
删除第一次出现指定元素的数据
public boolean remove(Object o) {
if (o == null) { 此处需要分成两步,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 void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
--size对size赋值,且给元素赋值null,利于gc回收
elementData[--size] = null; // clear to let GC do its work
}
ArrayList内部类也有一个remove方法,使用迭代器的remove在遍历中删除是正确的
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount; 此处会进行赋值
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
换成2会报错,在ArrayList里面实行迭代删除,foreach循环本质其实就是iterator,当执行iterator.next()时,会触发checkForComodification
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
而不用list.remove,而使用iterator,remove时会执行
expectedModCount = modCount;
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
①实例分析
foreach在ArrayList中本质代码如下
public class TTTT {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
Iterator iterator = list.iterator();
while (iterator.hasNext()){
String str = (String) iterator.next();
if("1".equals(str)){ “1”换成“2”则报错
list.remove(str);
}
}
}
}
流程:①当list添加两个元素之后又,modcount变成2
②list.iterator(); 这一步return new Itr(); Itr类有三个内部属性
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount; 把modcount赋给expectedModCount
③iterator.hasNext() 判断 return cursor != size;,此时cusor=0,size =2,返回true
④iterator.next(); 执行checkForComodification,
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
},此时两者均为2,肯定相等的,然后把cursor 赋值给i
public E next() {
checkForComodification();
int i = cursor; 此时 i = 0
if (i >= size) 此时i=0,size=2
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData; elementData中值为{1,2}
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1; 此时cursor = 1
return (E) elementData[lastRet = i]; 此时lastRet = 0 , 返回 elementData[0],即1
}
⑤ list.remove
public boolean remove(Object o) { 此时 0 = "1"
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); 执行此处fastremove,index=0
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++; 此时modCount = 3
int numMoved = size - index - 1; numMoved = 1
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
执行fastRemove,index=0, numMoved=1,执行System.arraycopy,把当前数组的1号位置元素复制到0号位置,此时elementData为 {2,2},最后给elementData[1]赋值null。,此时elementData{2},size为1。
⑥ 后面再执行iterator.hasNext()
此时cursor = size = 1,运行一次
问题关键所在: if (modCount != expectedModCount)
throw new ConcurrentModificationException();
},因为expectedModCount只赋值过一次,而modcount进行remove一次,
modcount就会进行改变,单线程删除倒数第二个不会发生异常。
当"1".equals(str)换成2时,modCount=3,expectedModCount=2