Java集合 ArrayList原理及使用
ArrayList是集合的一種實現,實現了接口List,List接口繼承了Collection接口。Collection是所有集合類的父類。ArrayList使用非常廣泛,不論是數據庫表查詢,excel導入解析,還是網站數據爬取都需要使用到,了解ArrayList原理及使用方法顯得非常重要。
一. 定義一個ArrayList
//默認創建一個ArrayList集合
List<String> list = new ArrayList<>();
//創建一個初始化長度為100的ArrayList集合
List<String> initlist = new ArrayList<>(100);
//將其他類型的集合轉為ArrayList
List<String> setList = new ArrayList<>(new HashSet());
我們讀一下源碼,看看定義ArrayList的過程到底做了什麼?
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] 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 = {};
/**
* 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
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
}
其實源碼裏面已經很清晰了,ArrayList非線程安全,底層是一個Object[],添加到ArrayList中的數據保存在了elementData屬性中。
-
當調用
new ArrayList<>()
時,將一個空數組{}賦值給了elementData,這個時候集合的長度size為默認長度0; -
當調用
new ArrayList<>(100)
時,根據傳入的長度,new一個Object[100]賦值給elementData,當然如果玩兒的話,傳了一個0,那麼將一個空數組{}賦值給了elementData; -
當調用new ArrayList<>(new HashSet())時,根據源碼,我們可知,可以傳遞任何實現了Collection接口的類,將傳遞的集合調用toArray()方法轉為數組內賦值給elementData;
注意:在傳入集合的ArrayList的構造方法中,有這樣一個判斷
if (elementData.getClass() != Object[].class),
給出的註釋是:c.toArray might (incorrectly) not return Object[] (see 6260652),即調用toArray方法返回的不一定是Object[]類型,查看ArrayList源碼
public Object[] toArray() { return Arrays.copyOf(elementData, size);}
我們發現返回的確實是Object[],那麼為什麼還會有這樣的判斷呢?
如果有一個類CustomList繼承了ArrayList,然後重寫了toArray()方法呢。。
public class CustomList<E> extends ArrayList {
@Override
public Integer [] toArray() {
return new Integer[]{1,2};
};
public static void main(String[] args) {
Object[] elementData = new CustomList<Integer>().toArray();
System.out.println(elementData.getClass());
System.out.println(Object[].class);
System.out.println(elementData.getClass() == Object[].class);
}
}
執行結果:
class [Ljava.lang.Integer;
class [Ljava.lang.Object;
false
接着說,如果傳入的集合類型和我們定義用來保存添加到集合中值的Object[]類型不一致時,ArrayList做了什麼處理?讀源碼看到,調用了Arrays.copyOf(elementData, size, Object[].class);
,繼續往下走
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
我們發現定義了一個新的數組,將原數組的數據拷貝到了新的數組中去。
二. ArrayList常用方法
ArrayList有很多常用方法,add,addAll,set,get,remove,size,isEmpty等
首先定義了一個ArrayList,
List<String> list = new ArrayList<>(10);
list.add('牛魔王');
list.add('蛟魔王');
...
list.add('美猴王');
Object[] elementData中數據如下:
1. add(E element)
我們通過源碼來看一下add(“白骨精”)到底發生了什麼
public boolean add(E e) {
ensureCapacityInternal(size + 1);
// Increments modCount!!
elementData[size++] = e;
return true;
}
首先通過 ensureCapacityInternal(size + 1)
來保證底層Object[]數組有足夠的空間存放添加的數據,然後將添加的數據存放到數組對應的位置上,我們看一下是怎麼保證數組有足夠的空間?
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_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);
}
這裏首先確定了Object[]足夠存放添加數據的最小容量,然後通過 grow(int minCapacity)
來進行數組擴容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.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);
}
擴容規則為“數組當前足夠的最小容量 + (數組當前足夠的最小容量 / 2)”,即數組當前足夠的最小容量 * 1.5,當然有最大值的限制。
因為最開始定義了集合容量為10,故而本次不會進行擴容,直接將第8個位置(從0開始,下標為7)設置為“白骨精”,這時Object[] elementData中數據如下:
還有和add()類似的方法。空間擴容原理都是一樣,如:
add("鐵扇", 0);
//將數組中的元素各自往後移動一位,再將“鐵扇”放到第一個位置上;
addAll(list..七個葫蘆娃);
//將集合{七個葫蘆娃}放到”白骨精”后,很明顯當前數組的容量已經不夠,需要擴容了,不執行該句代碼了;
addAll(list..哪吒三兄弟, 4);
//從第五個位置將“哪吒三兄弟”插進去,那麼數組第五個位置后的元素都需往後移動三位,數組按規則擴容為18。指定了插入位置的,會通過rangeCheckForAdd(int index)方法判斷是否數組越界
2. set(int index, E element)
因為ArrayList底層是由數組實現的,set實現非常簡單,調用 set(8, "豬八戒")
通過傳入的数字下標找到對應的位置,替換其中的元素,前提也需要首先判斷傳入的數組下標是否越界。將“獼猴王”替換為“豬八戒”。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
//返回值“獼猴王”,當前數組中數據:
3. get(int index)
ArrayList中get方法也非常簡單,通過下標查找即可,同時需要進行了類型轉換,因為數組為Object[],前提是需要判斷傳入的數組下標是否越界。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
調用get(6)返回”哪吒“。
4. remove(int index)
首先說一下ArrayList通過下標刪除的方法,我們看一下源碼
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
通過源碼我們可以看到首先獲取了待刪除的元素,並最終返回了。其次計算了數組中需要移動的位數 size – index – 1,那麼很明顯我們可以得出待刪除的是最後一個元素的話,移到位數為0,否則移動位數大於0,那麼通過數組元素的拷貝來實現往前移動相應位數。
如remove(10),找到的元素為“美猴王”,那麼移動位數 = 12-10-1 = 1;此時將原本在第12個位置上(數組下標為11)的“白骨精”往前移動一位,同時設置elementData[11] = null;這裏通過設置null值讓GC起作用。
5. remove(Object o)
刪除ArrayList中的值對象,其實和通過下標刪除很相似,只是多了一個步驟,遍歷底層數組elementData,通過equals()方法或 == (特殊情況下)來找到要刪除的元素,獲取其下標,調用remove(int index)一樣的代碼即可。
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
6. 其他方法
size() : 獲取集合長度,通過定義在ArrayList中的私有變量size得到
isEmpty():是否為空,通過定義在ArrayList中的私有變量size得到
contains(Object o):是否包含某個元素,通過遍歷底層數組elementData,通過equals或==進行判斷
clear():集合清空,通過遍歷底層數組elementData,設置為null
三. 總結
本文主要講解了ArrayList原理,從底層數組着手,講解了ArrayList定義時到底發生了什麼,再添加元素時,擴容規則如何,刪除元素時,數組的元素的移動方式以及一些常用方法的用途,若有不對之處,請批評指正,望共同進步,謝謝!
【精選推薦文章】
自行創業 缺乏曝光? 下一步"網站設計"幫您第一時間規劃公司的門面形象
網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!
評比前十大台北網頁設計、台北網站設計公司知名案例作品心得分享
台北網頁設計公司這麼多,該如何挑選?? 網頁設計報價省錢懶人包"嚨底家"