Reputation: 20208
In Java, is there any way to determine what initial capacity was used to create a Collection?
So when a collection was created like this:
List<Object> objectList = new ArrayList<Object>(5);
Is there any way to tell the objectList
was created with an initial capacity of 5?
Upvotes: 1
Views: 931
Reputation: 1
You cannot. Even if you added items to the collection, the array resulting from "toArray(...)" would only be the length of the items added. Also, size() will only return the number of elements added.
Upvotes: 0
Reputation: 12205
As far as I could see in the API, no such method exists.
But what you can is to subclass ArrayList, like this:
class MyArrayList<T> extends ArrayList<T> {
private final int initialCapacity;
public MyArrayList(final Integer initialCapacity) {
super(initialCapacity);
this.initialCapacity = initialCapacity;
}
public Integer getInitialCapacity() {
return this.initialCapacity;
}
}
Then you can do this:
final List<Integer> li = new MyArrayList<Integer>(5);
((MyArrayList) li).getInitialCapacity();
Upvotes: 0
Reputation: 139931
No, the ArrayList class at least does not keep track of the originalCapacity value passed in.
If you are worried about operations on the ArrayList requiring resizing of the internal array, you can always call ArrayList.ensureCapacity(int)
.
Upvotes: 5