我试图从这里了解Java中ArrayList类的添加操作。下面是部分代码:
//Proprties:
107 /**
108 * The array buffer into which the elements of the ArrayList are stored.
109 * The capacity of the ArrayList is the length of this array buffer.
110 */
111 private transient Object[] elementData;
112
113 /**
114 * The size of the ArrayList (the number of elements it contains).
115 *
116 * @serial
117 */
118 private int size;
404 /**
405 * Appends the specified element to the end of this list.
406 *
407 * @param e element to be appended to this list
408 * @return <tt>true</tt> (as specified by {@link Collection#add})
409 */
410 public boolean add(E e) {
411 ensureCapacityInternal(size + 1); // Increments modCount!!
412 elementData[size++] = e;
413 return true;
414 }
183 private void ensureCapacityInternal(int minCapacity) {
184 modCount++;
185 // overflow-conscious code
186 if (minCapacity - elementData.length > 0)
187 grow(minCapacity);
188 }
198 /**
199 * Increases the capacity to ensure that it can hold at least the
200 * number of elements specified by the minimum capacity argument.
201 *
202 * @param minCapacity the desired minimum capacity
203 */
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 }
Run Code Online (Sandbox Code Playgroud)
元素插入的步骤是:在插入新元素之前通过调用ensureCapacityInternal验证它是否确实存在足够的空间,如果没有足够的空间,我们调用增长操作来增加 elementData 容量。
我的问题是我看不到增长操作中newCapacity - minCapacity < 0条件将得到满足的情况。
你能向我解释这个条件的效用或给出一个满足这个条件的例子吗?
我的问题是我看不到增长操作中 newCapacity - minCapacity < 0 条件将得到满足的情况。
你能向我解释这个条件的效用或给出一个满足这个条件的例子吗?
发生整数溢出的情况怎么办?这是最好的情况,它描述了 ArrayList 不能进一步增长。
| 归档时间: |
|
| 查看次数: |
497 次 |
| 最近记录: |