1

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?

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
  • 2
    It could be interesting to know why you want this. – Denys Séguret Aug 30 '12 at 15:29
  • 1
    If you want to know the current capacity of the ArrayList, this question may be interesting. http://stackoverflow.com/questions/3564837/capacity-of-arraylist One of the answers has a reflection hack that can get the capacity. Not really a good idea though. – Jimbali Aug 30 '12 at 15:37
  • @dystroy I was just wondering why you can set it but can't check on how much allocated space is left. – Jasper de Vries Aug 30 '12 at 15:45
  • 2
    The reason is that it's mainly an implementation detail. You can give an hint about how much you need but, in accord with encapsulation principles, you shouldn't know how it is inside. – Denys Séguret Aug 30 '12 at 15:48

3 Answers3

5

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).

matt b
  • 138,234
  • 66
  • 282
  • 345
  • So, there is no way to tell if you 'need' to call `ensureCapacity`. I guess you don't need to know that then. – Jasper de Vries Aug 30 '12 at 15:49
  • 2
    @Jasper If you call `ensureCapacity` when the internal array is already sufficiently large, it just doesn't do anything. This doesn't cost you any more than calling some hypothetical function to check the size would anyway. – verdesmarald Aug 30 '12 at 15:52
0

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();
Tobb
  • 11,850
  • 6
  • 52
  • 77
0

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.

erdudley
  • 1
  • 1