直接上结果:初始化大小为0,存入10个以下元素,会将容量扩展至默认值10。当大小从10增加到11时,容量变成了15,扩大了1.5倍,以此类推,总是会扩容1.5倍,不为整则向下取整。
前几次扩容的数据: 0 >> 10 >> 15 >> 22 >> 33 >> 49 ...
import java.lang.reflect.Field;
import java.util.ArrayList;
public class ArrayList_Test
{
public static void main(String[] args){
ArrayList<Integer> squares = new ArrayList<Integer>();
for (int i = 1; i <= 35; i++)
squares.add(i);
Class c=((Object)squares).getClass();
Field f;
try {
f = c.getDeclaredField("elementData");
f.setAccessible(true);
try {
Object[] o=(Object[]) f.get(squares);
System.out.println(o.length);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}