继承体系,实现双端队列,内部是链表结构
ArrayList中关键字段说明
private static final int DEFAULT_CAPACITY = 10; //默认初始化的容量为10 private static final Object[] EMPTY_ELEMENTDATA = {}; //空数组实例 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //不提供初始容器大小时候,默认的空数组 transient Object[] elementData; //实际存放元素的数组 private int size; //数组大小添加元素实现
确定添加元素后确定是否越界如果越界:进行扩容,每次扩容大小为原来的1.5倍,如果还不满足,则直接扩容到所需的最小容量,进行数组复制将新元素添加到最后的元素后面 public boolean add(E e) { ensureCapacityInternal(size + 1); //确实是否需要扩容 elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } // 在没有给定初始化容器大小的时候,默认赋值 private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code 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; //扩容后大小仍不满足,则直接扩容到minCapacity,一般addAll()情况下,可能出现 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); //赋值数组 }