Possible Duplicate:
How to get the capacity of the ArrayList in Java?
How to find the capacity of an ArrayList
?
I'm curious, what do you need it for? You should know that the capacity is not (as it may sound) an upper limit of how much you can put into the ArrayList. It's a value representing how much data you can put into the list, without forcing it to reallocate it internal array. Basically, the notion of capacity is only there in order for you to tweak the performance slightly.
Anyway, perhaps you already know that, so here comes the actual answer.
The interface provided by API for ArrayList simply doesn't support such use case. There are many reasons for this. One reason is that you shouldn't care about this. The ArrayList is to be thought of as an unbounded array which abstracts away from details such as capacity.
The closest you can get to controlling the capacity is through the constructor ArrayList(int initialCapacity)
, and the two methods trimToSize()
and ensureCapacity(int minCapacity)
.
For fun however, I managed to solve it through an ugly reflection-hack (don't use this):
import java.lang.reflect.Field;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>(3);
for (int i = 0; i < 17; i++) {
list.add(i);
System.out.format("Size: %2d, Capacity: %2d%n",
list.size(), getCapacity(list));
}
}
static int getCapacity(ArrayList<?> l) throws Exception {
Field dataField = ArrayList.class.getDeclaredField("elementData");
dataField.setAccessible(true);
return ((Object[]) dataField.get(l)).length;
}
}
Output:
Size: 1, Capacity: 3
Size: 2, Capacity: 3
Size: 3, Capacity: 3
Size: 4, Capacity: 5
Size: 5, Capacity: 5
Size: 6, Capacity: 8
Size: 7, Capacity: 8
Size: 8, Capacity: 8
Size: 9, Capacity: 13
Size: 10, Capacity: 13
Size: 11, Capacity: 13
Size: 12, Capacity: 13
Size: 13, Capacity: 13
Size: 14, Capacity: 20
Size: 15, Capacity: 20
Size: 16, Capacity: 20
Size: 17, Capacity: 20