Search code examples
javaarraylistcollectionsabstraction

Why trimToSize/ensureCapacity methods provide 'public' level access?


Any user who would like to access the java.util.ArrayList facility, has to obey the usage contract provided in java.util.List.

But one can break this usage contract easily and access the methods trimToSize

public void trimToSize() { ... }

and ensureCapacity

public void ensureCapacity(int minCapacity) { ...}

Because these two methods are neither overridden from java.util.AbstractList nor implemented from java.util.List.

So, Why these two methods provide public level access and break the abstraction provided by java.util.List?


Solution

  • There are some cases where efficiency may cost more than data abstraction. The ensureCapacity may be used to preallocate the internal buffer once when you are about to add known number of elements. The trimToSize may be used when you are not going to add more elements to free wasted memory. Both methods are non-applicable to other List implementations, thus they are added to ArrayList only.

    Note that usually list is created and initially populated by one method which knows what implementation is used. So this does not break abstraction. For example, consider such code:

    public List<String> createList() {
        ArrayList<String> list = new ArrayList<>();
        // populate the list
        list.trimToSize();
        return list;
    }
    

    This way you can save the memory and still return the List interace.