整体类图
ArrayList
重要知识点
- 底层数组存放数据,默认大小10,最大大小
MAX_ARRAY_SIZE
为Integer.MAX_VALUE - 8
, 每次扩容1.5倍(当然会有一些检查,扩容1.5倍之后还小于minCapacity
,则使用minCapacity
;超过最大大小,则使用hugeCapacity(minCapacity)
等等)
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);
}
- get、set复杂度O(1),add(E e)复杂度O(1),add(int index, E element)由于需要将index之后的数据后移一位,复杂度O(n), remove(int index)也是O(n)
- 可以存放null
- 线程不安全
- 其他一些东西就比较简单了
线程不安全的原因
所有操作没有加锁所以线程不安全。
public Iterator<E> iterator() {
return new Itr();
}
可见通过内部类实现了遍历器,所以在遍历ArrayList时(for遍历、Iterator遍历等等),实际上都是使用这个Itr
Itr
的关键代码如下:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {
}
public boolean hasNext() {
return cursor != size;
}