Its known that Java ArrayList is implemented using arrays and initializes with capacity of 10 and increases its size by 50% . How to get the current ArrayList capacity not t
You can get it by reflection:
public abstract class ArrayListHelper {
static final Field field;
static {
try {
field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("unchecked")
public static int getArrayListCapacity(ArrayList arrayList) {
try {
final E[] elementData = (E[]) field.get(arrayList);
return elementData.length;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}