public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//外部操作数
protected transient int modCount = 0;//2
}
public class ArrayList<E> extends AbstractList<E> implements List<E>{
//默认容量
private static final int DEFAULT_CAPACITY = 10;
//空内容的数组(长度为0的数组)
private static final Object[] EMPTY_ELEMENTDATA = {};
//默认容量空内容的数字(长度为0的数组)
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//元素容器
transient Object[] elementData;//new Object[10]{张三,李四,null,null,null,...}
//元素个数
private int size;//2
//最大的数组长度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
//initialCapacity - 100
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);
}
}
//e - 李四
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//minCapacity - 2
private void ensureCapacityInternal(int minCapacity) {
//使用无参构造创建对象,第一次添加元素时进入的判断
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
//minCapacity - 10
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
//minCapacity - 2
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
//minCapacity - 10
private void grow(int minCapacity) {
//oldCapacity - 0
int oldCapacity = elementData.length;
//newCapacity - 0
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
//newCapacity - 10
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//数组的扩容
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;
}
}
ArrayList<String> list = new ArrayList<>();
//ArrayList<String> list = new ArrayList<>(10000);
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
标签:int,MAX,ArrayList,elementData,private,minCapacity,源码,底层 From: https://blog.51cto.com/u_16154651/6530464
- ArrayList默认容量是多少?
10
- ArrayList的数据结构是什么?
Object类型的一维数组 -- --------Object[] elementData;
- ArrayList容器的最大容量是多少?
Integer.MAX_VALUE-8
- ArrayList容器的最大容量为什么是Integer.MAX_VALUE-8?
减8的位置是用于存储数组的头部信息
- 什么时候创建ArrayList集合直接指定初始化容量?
ArrayList list = new ArrayList<>(10000);
当你需要存储大量的数据时
因为使用无参构造创建ArrayList对象,默认容量为10,存储大量数据时会存在多次扩容的情况,扩容效率低。所以我们在存储大量数据时,使用有参构造直接设置ArrayList底层数组的大小,减少扩容次数,从而提高程序性能
- ArrayList的扩容机制?
原来长度的1.5倍如何看集合源码?
- 找场景
- 关注继承关系
- 关注成员属性
- 关注创建对象的过程
- 关注添加元素的过程(考虑是否扩容)