標籤:from 而在 font inflate 依次 UI array pad nested
ArrayList在Java中主要是以線性表的形式進行儲存,其本質是數組,不過相對於數組的長度不可變這一缺點,其實行了長度可變策略,使你在使用時,感覺到其就是一個無限長度的數組,而在底層中,則是通過動態增加長度來實現的,ArrayList就像是排隊,沒來一個對象或者元素,都會被添加到末尾位置(預設情況下),當然也免不了熟人插隊的情況,此時就要指定相應位置,位置之前的元素位置不變,位置之後的元素依次後遺一位。
ArrayLsit.class源碼解析
由於源碼函數較多,這裡通過一個列子來解析一下背後的原理就行了。
public class ArrayListAndHashSet { public static void main(String[] args) { Person p1 = new Person("Jim", "One"); Person p2 = new Person("Bob", "two"); Person p3 = new Person("Jim", "One"); // 測試List List<Person> persons = new ArrayList<>(); persons.add(p1); persons.add(p2); persons.add(p3); persons.add(p1); System.out.println("persons.size() = " + persons.size());
- List<Person> presons = new ArrayList<>();
這句執行了ArrayList的無參建構函式:
/** * Constructs an empty list with an initial capacity of ten. */public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}
通過無參建構函式,我們可以發現將elementData賦值為了DEFAULTCAPACITY_EMPTY_ELEMENTDATA,這個常量在源碼中代表的含義是:
/** * Shared empty array instance used for default sized empty instances. We * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when * first element is added. */private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
通過注釋我們可以發現其是一個空的執行個體對象,為了和EMPTY_ELEMENTDATA進行區分用的,
然後是我們的elementData,通過注釋可發現,當第一個元素被加進來的時候,數組的緩衝長度將會變成DEFAULT_CAPACITY
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */transient Object[] elementData; // non-private to simplify nested class access
DEFAULT_CAPACITY的預設值是10
/** * Default initial capacity. */private static final int DEFAULT_CAPACITY = 10;
JAVA_ArrayList和HashSet