0

I have the following class:

class CapacityTrackingArrayList<T> extends ArrayList<T>
{
public boolean add(T elem)
{
    System.out.printf("Invoking add()... \n");
    boolean isAdded = super.add(elem);
    return isAdded;
}

public void ensureCapacity(int arg)
{
    System.out.printf("Invoking ensureCapacity(%d)... \n", arg);
    super.ensureCapacity(arg);
}
}  // class CapacityTrackingArrayList

and testing with...

CapacityTrackingArrayList<Integer> numberList2 = new CapacityTrackingArrayList<Integer>();
numberList2.ensureCapacity(100);
for (int i = 0; i <= 5; i++)
{
    numberList2.add(i);
}

I get following output

Invoking ensureCapacity(100)... 
Invoking ensureCapacity(1)... 
Invoking add()... 
Invoking ensureCapacity(2)... 
Invoking add()... 
Invoking ensureCapacity(3)... 
Invoking add()... 
Invoking ensureCapacity(4)... 
Invoking add()... 
Invoking ensureCapacity(5)... 

What strikes me is that, even though I call

numberList2.ensureCapacity(100);

before adding, I would expect the list to keep this capacity until about 100 elements have been added.

Apparently, not at all!

Always, when adding an element, it invokes ensureCapacity(). How come?

Blue Ice
  • 7,888
  • 6
  • 32
  • 52
Chris
  • 117
  • 1
  • 5

1 Answers1

4

before adding, I would expect the list to keep this capacity until about 100 elements have been added. ... Apparently, not at all!

I don't see you printing the current capacity anywhere (you can't, by the way, unless you hack it with reflection, which is unreliable at best, but temporarily useful in your experiment). You're only printing requests.

Always, when adding an element, it invokes ensureCapacity(). How come?

To ensure that the list has the capacity to hold the new element that is being added. This doesn't mean it will actually decrease the capacity, it only needs to make sure that the capacity is at least large enough to hold the new item.

See the source for ArrayList.ensureCapacity() to get an idea of what is going on.

In reality, though, there isn't much reason for you to be concerned with what the capacity actually is; you have ensureCapacity() and trimToSize() with contracted behaviors, these will generally serve your needs.

randy
  • 369
  • 4
  • 12
Jason C
  • 38,729
  • 14
  • 126
  • 182