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 use Vector instead of ArrayList. Vector supports capacity() method.
Looking at ArrayList's spec I see no method that provides this information.
That said, the ensureCapacity method does seem like a step in the right direction (caution: it is does not guarantee a correct answer): When called it ensures that the capacity is at least the specified argument. So, if the ArrayList
implementation uses this method to ensure capacity (as opposed to calling some private method/manipulating the relevant fields directly) you can obtain the current capacity by overriding this method. You also need to override trimToSize()
in a similar manner.
Of course, this solution is not very portable as a different implementation of ArrayList
(on a JVM from another vendor) may do things differently.
Here's how the code should look like
public class CapacityTrackingArrayList<T> extends ArrayList<T> {
// declare a constructor for each ArrayList constructor ...
// Now, capacity tracking stuff:
private int currentCapacity = 10;
public int getCapacity() { return currentCapacity; }
public void ensureCapacity(int arg) {
currentCapacity = arg;
super.ensureCapacity(arg);
}
public void trimToSize() { currentCapacity = size(); super.trimToSize(); }
}
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 <E> int getArrayListCapacity(ArrayList<E> arrayList) {
try {
final E[] elementData = (E[]) field.get(arrayList);
return elementData.length;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}