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 the current capacity of an ArrayList in Java using reflection. Here is an example:
package examples1;
import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Field;
public class Numbers {
public static void main(String[] args) throws Exception {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
System.out.println(getCapacity(numbers));
}
static int getCapacity(List al) throws Exception {
Field field = ArrayList.class.getDeclaredField("elementData");
field.setAccessible(true);
return ((Object[]) field.get(al)).length;
}
}
This will output: 10
Notes:
getCapacity()
method modified from the original at http://javaonlineguide.net/2015/08/find-capacity-of-an-arraylist-in-java-size-vs-capacity-in-java-list-example.html0
To force a capacity without adding, pass it in the constructor like so:
List<Integer> numbers = new ArrayList<>(20);
The whole point of using ArrayList is to dynamically add new element, So there is no specific method to get the capacity of the ArrayList.
Every time we add an element dynamically causes reallocation and since reallocation is costly in terms of time, preventing reallocation improves performance and hence you can manually increase the capacity of ArrayList by calling ensureCapacity() but again you can not find out the capacity of the ArrayList.
Default capacity of ArrayList
is 10.once the max size is reached,new capacity will be:
new capacity=(currentcapacity*3/2)+1.
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.
I just checked out the sun documentation on the ArrayList class, and the only method I saw that related to the capacity was ensureCapacity(int minCapacity), which is not exactly what you want. Good luck!
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.