ArrayList
サイズを気にしなくていいのもポイントです。より多くのアイテムが追加されると、動的にサイズが変更されます。のソースコードを見ることができますadd
:
410 public boolean add(E e) {
411 ensureCapacityInternal(size + 1); // Increments modCount!!
412 elementData[size++] = e;
413 return true;
414 }
ensureCapacityInternal
:
183 private void ensureCapacityInternal(int minCapacity) {
184 modCount++;
185 // overflow-conscious code
186 if (minCapacity - elementData.length > 0)
187 grow(minCapacity);
188 }
とgrow
:
204 private void grow(int minCapacity) {
205 // overflow-conscious code
206 int oldCapacity = elementData.length;
207 int newCapacity = oldCapacity + (oldCapacity >> 1);
208 if (newCapacity - minCapacity < 0)
209 newCapacity = minCapacity;
210 if (newCapacity - MAX_ARRAY_SIZE > 0)
211 newCapacity = hugeCapacity(minCapacity);
212 // minCapacity is usually close to size, so this is a win:
213 elementData = Arrays.copyOf(elementData, newCapacity);
214 }