Hi, 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 the Size of the ArrayList.
Thx
Hi, 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 the Size of the ArrayList.
Thx
I don't think this is possible. What is your use case? I believe C# ArrayLists have a .capacity property, but the Java ArrayList class doesn't expose this information.
You have the constructor that takes an initial capacity argument, and you have the ensureCapacity() method which you could use to reduce the amount of incremental reallocation.
You also have the trimToSize() method you can use if you are really worried about memory usage.
Don't remember if it has but you could do it yourself by looking at the source code of ArrayList. Java developers should take advantage of the source code bundled with the SDK.
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);
}
}
}
How to get the current ArrayList capacity not the Size of the ArrayList.
Why exactly would you ever need to know?