通过反射获取ArrayList的容量
public static int getArrayListLength(ArrayList<String> list) throws Exception {
//获取class对象
Class<?> arraylist = Class.forName("java.util.ArrayList");
//获取属性elementData数组
Field elementData = arraylist.getDeclaredField("elementData");
//设置访问状态为true
elementData.setAccessible(true);
//获取指定对象此Filed的值
Object[] objects = (Object[]) elementData.get(list);
return objects.length;
}
测试容量
public static void main(String[] args) throws Exception {
//创建一个存储字符串的集合,
ArrayList<String> list = new ArrayList<>();
// 存储16个字符串元素,
list.add("张飞");
list.add("刘备");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
list.add("关羽");
int rongliang = getArrayListLength(list);
System.out.println(rongliang);//22
}
总结:ArrayList默认容量10,扩容为当前容积一半(15+7).
标签:容量,关羽,ArrayList,elementData,list,获取,add From: https://www.cnblogs.com/OKGOsky/p/17011246.html