Skip to content

Commit

Permalink
修复ArrayList扩容机制的问题
Browse files Browse the repository at this point in the history
对于奇数Old Capacity,右移操作:new Capacity = 1.5*Old Capacity - 0.5
  • Loading branch information
Xunzhuo authored Nov 18, 2020
1 parent 3697796 commit bc23085
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion notes/Java 容器.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ private static final int DEFAULT_CAPACITY = 10;

#### 2. 扩容

添加元素时使用 ensureCapacityInternal() 方法来保证容量足够,如果不够时,需要使用 grow() 方法进行扩容,新容量的大小为 `oldCapacity + (oldCapacity \>\> 1)`,也就是旧容量的 1.5
添加元素时使用 ensureCapacityInternal() 方法来保证容量足够,如果不够时,需要使用 grow() 方法进行扩容,新容量的大小为 `oldCapacity + (oldCapacity >> 1)`,也就是旧容量的 1.5 倍左右,(oldCapacity 为偶数就是 1.5 倍,oldCapacity为奇数就是 1.5 倍-0.5)。奇偶不同,比如 :8+8/2 = 12, 13+13/2=19,如果是奇数的话会丢掉小数

扩容操作需要调用 `Arrays.copyOf()` 把原数组整个复制到新数组中,这个操作代价很高,因此最好在创建 ArrayList 对象时就指定大概的容量大小,减少扩容操作的次数。

Expand Down

0 comments on commit bc23085

Please sign in to comment.