// 扩容,每次增加原来一半的容量 privatevoidgrow(){ // 右移的时候一定要加括号,>>的优先级低于+, // 为了避免size为0,取扩容后的size和默认容量两者的最大值为新的容量 int newCapacity = Math.max(size + (size >> 1), DEFAULT_CAPACITY); Object[] newElementData = new Object[newCapacity]; for (int i = 0; i < size; i++) { newElementData[i] = elementData[i]; } elementData = newElementData; }
// 判断索引值是否为正确的元素索引 privatevoidcheckElementIndex(int index){ if (index < 0 || index >= size) { thrownew IndexOutOfBoundsException("index:" + index + ",size:" + size); } }
// 可以添加元素的位置,索引从0开始到size privatevoidcheckPositionIndex(int index){ if (index < 0 || index > size) { thrownew IndexOutOfBoundsException("index:" + index + ",size:" + size); } }
@Override public String toString(){ StringBuilder list = new StringBuilder(); list.append("ArrayList ["); for (int i = 0; i < size; i++) { list.append(elementData[i]); if (i < size - 1) { list.append(','); } } list.append("]"); return list.toString(); } }