New ArrayList ()
The default initialization length for JDK version 1.5 is 10.
1.7 and up is 0, the default is 10 (or larger) when the element is added. Why is it so designed that it is not directly initialized to 10 as long as 1.5?
1.5 Defines the length of the array directly as 10,
The source code is as follows
public ArrayList (int initialcapacity) {super (); if (initialcapacity < 0) throw new IllegalArgumentException ("Illegal capacity:" + initialcapacity); this.elementdata = (e[]) new object[initialcapacity];} /** * Constructs an empty list with an initial capacity of ten. */public ArrayList () {this (ten);}
1.7 defines the length of the array as 0, until the Add or AddAll method executes the expansion to 10 (or greater),
source as follows
//Initialize
Public ArrayList () {this.elementdata = Defaultcapacity_empty_elementdata; }//Add Element public boolean add (E o) {ensurecapacity (size + 1); Increments modcount!! elementdata[size++] = o; return true; }//expansion check private void ensurecapacityinternal (int mincapacity) {if (Elementdata = = Defaultcapacity_emp Ty_elementdata) {mincapacity = Math.max (default_capacity, mincapacity); } ensureexplicitcapacity (mincapacity); } private void ensureexplicitcapacity (int mincapacity) {modcount++; Overflow-conscious code if (mincapacity-elementdata.length > 0) grow (mincapacity); }//capacity private void grow (int mincapacity) {//overflow-conscious code int oldcapacity = Element Data.length; int newcapacity = oldcapacity + (oldcapacity >> 1); if (newcapacity-mincapacity < 0) newcapacity = mincapacity; if (NEWCAPacity-max_array_size > 0) newcapacity = hugecapacity (mincapacity); Mincapacity is usually close to size, so this is a win:elementdata = arrays.copyof (Elementdata, newcapacity); } ' 1.8 with 1.7 excuse me why, why not directly defined as 10 as 1.5?
Java Source Code Anatomy series--arraylist () initialization length