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
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.
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);
}
}
}
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);
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(); }
}
Default capacity of ArrayList
is 10.once the max size is reached,new capacity will be:
new capacity=(currentcapacity*3/2)+1.
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.
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.
The default capacity is 2 for an Array List in java. I am not able to find the vague documentation I read a while ago. But the size will be zero upon initialization. Once we add the third element it will creates an array of double the capacity in another memory location. The reference will be shifted accordingly and the previous array will be garbage collected
I dont think there is a direct method to check ArrayList Capacity. But, there is a method to Check the Size of the array list.
s.o.p.ln(arraylist.size());
You can say this in interview. We cannot tell the ArrayList Capacity, but we can check the Size. Then, according to the size, we can calculate the Capacity by our own. Initial Capacity of Arraylist = 10. When it is full, new List is formed with a Capacity of CurrentCapacity * (3/2) +1 . So, in this method, you can calculate the capacity of ArrayList.