Fred 2022年2月20日 时间
环境JDK1.8 这谁写的代码 一看是JDK源码
话不多说上图镇楼 PS: 如有误导敬请见谅 毕竟是个**草稿**
SHOW ME TEH CODE
try {
List<Integer> list = new ArrayList<>(0); // 这里也可以不填 也可以随便填着玩
Class<? extends List> aClass = list.getClass();
Field elementData = aClass.getDeclaredField("elementData");
elementData.setAccessible(true);
Object[] e;
System.out.println("i: 0 | e.length: 0 | ");
for (int i = 0; i < 10; ++i) {
list.add(0);
e = (Object[])elementData.get(list); // 经典水中捞月
System.out.printf("i:%2d | e.length:%2d | (oldCapacity >> 1):%2d\n", i + 1, e.length, e.length >> 1);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
结果如下:
i: 0 | e.length: 0 |
/***************************************************************************
* 如果 oldCapacity 开始较小 (oldCapacity >> 1) 基本没用
* 靠的是 ensureCapacityInternal(size + 1)
***************************************************************************/
i: 1 | e.length: 1 | (oldCapacity >> 1): 0
i: 2 | e.length: 2 | (oldCapacity >> 1): 1
i: 3 | e.length: 3 | (oldCapacity >> 1): 1
i: 4 | e.length: 4 | (oldCapacity >> 1): 2 // 这里开始发力了
i: 5 | e.length: 6 | (oldCapacity >> 1): 3
i: 6 | e.length: 6 | (oldCapacity >> 1): 3 // 越来越猛了
i: 7 | e.length: 9 | (oldCapacity >> 1): 4
i: 8 | e.length: 9 | (oldCapacity >> 1): 4
i: 9 | e.length: 9 | (oldCapacity >> 1): 4 // 为啥不是准1.5倍的原因 @ 0b1001 >>> 1 = 0b100
i:10 | e.length:13 | (oldCapacity >> 1): 6Process finished with exit code 0