java - Why trimToSize/ensureCapacity methods provide 'public' level access? -
any user access java.util.arraylist
facility, has obey usage contract provided in java.util.list
.
but 1 can break usage contract , access methods trimtosize
public void trimtosize() { ... }
and ensurecapacity
public void ensurecapacity(int mincapacity) { ...}
because these 2 methods neither overridden java.util.abstractlist
nor implemented java.util.list
.
so, why these 2 methods provide public
level access , break abstraction provided java.util.list
?
there cases efficiency may cost more data abstraction. ensurecapacity
may used preallocate internal buffer once when add known number of elements. trimtosize
may used when not going add more elements free wasted memory. both methods non-applicable other list
implementations, added arraylist
only.
note list created , populated 1 method knows implementation used. not break abstraction. example, consider such code:
public list<string> createlist() { arraylist<string> list = new arraylist<>(); // populate list list.trimtosize(); return list; }
this way can save memory , still return list
interace.
Comments
Post a Comment