ArrayList扩容
代码演示ArrayList扩容
反射获取底层数组elementData
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
private static int getCapacity(ArrayList<Integer> list) {
// 反射获取ArrayList底层private数组大小
Integer length = null;
Class c = list.getClass();
Field f;
try {
f = c.getDeclaredField("elementData");
f.setAccessible(true);
Object[] o = new Object[0];
try {
o = (Object[]) f.get(list);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
length = o.length;
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // elementData: 底层数组名
return length;
}
}
初始容量
- 未添加任何元素,数组默认为空数组
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
int len = getCapacity(list);
int size = list.size();
System.out.println("ArrayList数组容量:" + len);
System.out.println("装载元素个数" + size);
}
- 添加小于10个元素【默认容量10】
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < 8; i++) {
list.add(i);
}
int len = getCapacity(list);
int size = list.size();
System.out.println("ArrayList数组容量:" + len);
System.out.println("装载元素个数" + size);
}
ArrayList数组容量:10
装载元素个数8
- 大于10
一次扩容,1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
ArrayList数组容量:15
装载元素个数11
- 大于15
上一次的15 + 15 / 2 = 15 + 7 = 22
ArrayList数组容量:22
装载元素个数16
- 接下来就是22 * 1.5 = 33
- 34的时候.49,
ArrayList数组容量:49
装载元素个数34