collection.add(ArrayList)源码分析 Posted on 2019-10-01 | In 我眼中的java | | 次阅读 相关源码截取如下: 12345678910111213141516171819202122232425262728293031323334353637383940public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! //size初始为0 elementData[size++] = e; return true;}private void ensureCapacityInternal(int minCapacity) {//为1 ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity);//设默认大小为10 } 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); 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;} 总结:ArrayList中存放的elementData仅是个对象数组,别无其他, Donate comment here Donate WeChat Pay Alipay Bitcoin