ArrayList初始化大小为10,getDeclaredField和getField的区别在于前者可以获取非public字段,而后者只能取得public字段
package org.hujian.jdk.list;
import org.hujian.common.JvmTestRunner;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Created on 2018/11/5 11:31.
*/
public class TestArrayListInitSize extends JvmTestRunner {
/**
* 在这里实现测试逻辑,不提供参数列表以及返回值,执行该方法应该测试到
* 你需要实现的所有逻辑,本方法单线程执行(main)
*/
@Override
protected void execute() {
//Constructs an empty list with an initial capacity of ten.
List<Integer> intList = new ArrayList<>();
System.out.println(getCapacity(intList));
intList.add(1);
System.out.println(getCapacity(intList));
}
private long getCapacity(List arrayList) {
try {
Field field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
return ((Object[])field.get(arrayList)).length;
} catch (NoSuchFieldException e) {
return -1;
} catch (IllegalAccessException e) {
return -2;
}
}
public static void main(String[] args) {
new TestArrayListInitSize().execute();
}
}