java - Default size of ArrayList -
looking through piece of code noticed 1 strange initialization of arraylist:
... = new arraylist<..>(0);
i've opened javase 7 sources , saw inner elementdata arrray initialized empty array constant - {}
. when pass capacity arraylist
constructor same - new object[0]
. question is: there difference between new arraylist(0)
, new arraylist()
? shouldn't arraylist
set default capacity size smth 10 ?
thanks answers.
an arraylist
has internal array store list elements.
there difference between 2 constructor calls in java 7 , 8:
if new arraylist<>(0)
arraylist
creates new object array of size 0.
if new arraylist<>()
arraylist
uses static empty object array of size 0 , switches own private array once add items list.
edit:
the javadoc of default arraylist
constructor seems contradict this.
/** * constructs empty list initial capacity of ten. */ public arraylist() { super(); this.elementdata = empty_defaultcapacity_empty_elementdata; // = static, empty }
but not create element array of length 10 immediately, instead when add elements or ensure capacity:
public void ensurecapacity(int mincapacity) { int minexpand = (elementdata != defaultcapacity_empty_elementdata) // size if not default element table ? 0 // larger default default empty table. it's // supposed @ default size. : default_capacity; // = 10 if (mincapacity > minexpand) { ensureexplicitcapacity(mincapacity); } }
Comments
Post a Comment