transient Object[] elementData; //存放数据 private int size; //记录已存放的元素个数 复制代码
//static 关键字标识,所有对象公用,省内存 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //初始化一个空的数组,在第一次add()时才初始化 elementData public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } //预知大数据时指定初始化容量,减少扩容次数 public ArrayList(int initialCapacity) { ... this.elementData = new Object[initialCapacity]; } 复制代码
//构造函数如下 public ArrayList(int initialCapacity) //LinkedList不是数组就没有 public HashMap(int initialCapacity) public StringBuffer(int capacity) 复制代码
private void grow(int minCapacity) { int oldCapacity = elementData.length; //1.5倍扩容 10->15->22->33 int newCapacity = oldCapacity + (oldCapacity >> 1); ... elementData = Arrays.copyOf(elementData, newCapacity); } //最终调用 System 类底层方法,浅拷贝数据 public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length); 复制代码
private boolean batchRemove(Collection<?> c, boolean complement) { ... try { for (; r < size; r++) //内层循环性能关键点,基于Hash查找的HashSet contains() 方法比 List快 if (c.contains(elementData[r]) == complement) //核心操作数据,jdk美妙之处 elementData[w++] = elementData[r]; } finally { ... } return modified; } 复制代码
//1.8 lambda 删除方式 public boolean removeIf(Predicate<? super E> filter) { final BitSet removeSet = new BitSet(size); for (int i=0; i < size; i++) if (filter.test(element)) { removeSet.set(i); } } 复制代码
transient Object[] elementData; 复制代码
private void writeObject(java.io.ObjectOutputStream s){ ... //结束位为size,省 内存|磁盘空间|带宽 for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } ... } private void readObject(java.io.ObjectInputStream s){ for (int i=0; i<size; i++) { //数据还原 elementData[i] = s.readObject(); } } } 复制代码
ConcurrentModificationException
* @see Collection * @see Iterator * @see Spliterator * @see ListIterator * @see Vector * @see LinkedList * @see HashSet * @see Hashtable * @see TreeMap * @see AbstractList * it is not generally permissible for one thread to modify a Collection * while another thread is iterating over it. * In general, the results of the iteration are undefined under these circumstances 复制代码
//涉及到修改 elementData 的方法执行 modCount++; public boolean add(E e) public E remove(int index) public void replaceAll(UnaryOperator<E> operator) public void sort(Comparator<? super E> c) 复制代码
//涉及遍历的方法校验 modCount 值 public void forEach(Consumer<? super E> action) { //遍历前记录修改次数 final int expectedModCount = modCount; for (int i=0; modCount == expectedModCount && i < size; i++) { ... } //发现和预期值不同则抛出异常 if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } public boolean removeIf(Predicate<? super E> filter) Itr.next() 复制代码
public void sort(Comparator<? super E> c) { ... //最终调用 TimSort.sort() ,组合 + 插入 排序 Arrays.sort((E[]) elementData, 0, size, c); } // 从大到小排列 ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); list.sort((a,b)-> b-a); 复制代码