java的集合是常用的類籽孙,也是面試官非常喜歡的問題。集合可以分為set集合、list集合和map集合list集合傲宜,這篇博客會分析list集合。時間非常緊迫的同學(xué)可以直接看最后的總結(jié)夫啊。
首先看一下List類的體系結(jié)構(gòu)函卒,JDK版本為1.8.0
List體系中有三個我們常用的類:ArrayList、Vector撇眯、LinkedList报嵌。
下面主意分析這三個類
ArrayList
ArrayList內(nèi)部使用數(shù)組來保存對象,在數(shù)組長度不夠的時候熊榛,增加數(shù)組的長度锚国。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
ArrayList繼承了AbstractList,實現(xiàn)了List玄坦、Random血筑、Colleable、Serializable接口营搅,ArrayList有一個泛型云挟,用來指定保存的對象類型。
ArrayList的成員變量
private static final long serialVersionUID = 8683452581122892189L;
/**
* 默認(rèn)的數(shù)組容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 默認(rèn)空數(shù)組
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 默認(rèn)空數(shù)組
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 用于保存數(shù)據(jù)的數(shù)組
* 不可序列化
*/
transient Object[] elementData; //
/**
* 當(dāng)前保存的數(shù)據(jù)數(shù)量
*
* @serial
*/
private int size;
ArrayList的構(gòu)造方法
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
無參構(gòu)造方法中將elementData默認(rèn)初始化為DEFAULTCAPACITY_EMPTY_ELEMENTDATA转质,也就是一個空的數(shù)組园欣。
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity]; //如果指定的初始容量initialCapacity大于0,就創(chuàng)建initialCapacity大小的數(shù)組
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA; //如果initialCapacity等于0休蟹,將elementData 初始化為空數(shù)組
} else {
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
}
}
一個參數(shù)int initialCapacity的構(gòu)造方法中沸枯,根據(jù)傳入的初始化容量,創(chuàng)建不同長度的數(shù)組赂弓。如果initialCapacity大于0绑榴,創(chuàng)建initialCapacity長度的數(shù)組;如果initialCapacity等于0盈魁,使elementData 指向一個長度為0的數(shù)組翔怎;如果initialCapacity長度小于0,拋出異常。
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray(); //將傳入的集合賦值給elementData
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;
}
}
一個參數(shù)Collection<? extends E> c的構(gòu)造方法赤套,將傳入的集合賦值給elementData飘痛,更新數(shù)組長度size。
容握?值得是泛型通配符宣脉,可以指代不同的泛型,具體可以看這一篇文章Java總結(jié)篇系列:Java泛型剔氏。
private void grow(int minCapacity)
grow方法是進(jìn)行l(wèi)ist中數(shù)組擴(kuò)容的塑猖,傳入當(dāng)前需要的最小數(shù)組長度。下面看源碼谈跛。
private void grow(int minCapacity) {
int oldCapacity = elementData.length; //獲得數(shù)組現(xiàn)有的長度
int newCapacity = oldCapacity + (oldCapacity >> 1); //數(shù)組新長度是現(xiàn)有長度的1.5倍
if (newCapacity - minCapacity < 0) //如果新長度仍然不滿足需求的長度
newCapacity = minCapacity; //就設(shè)置新長度為需求的長度
if (newCapacity - MAX_ARRAY_SIZE > 0) //如果長度超過所能承受的最大長度Integer.MAX_VALUE - 8
newCapacity = hugeCapacity(minCapacity); //使用hugeCapacity方法設(shè)置新長度
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity); //復(fù)制數(shù)組元素
}
上面程序中首先獲得數(shù)組的現(xiàn)有長度羊苟,然后設(shè)置數(shù)組新長度是現(xiàn)有長度的1.5倍,如果新長度仍小于所需長度币旧,則設(shè)置新長度等于所需長度践险。如果新長度大于最大長度,則使用hugeCapacity方法設(shè)置新長度吹菱。下面看hugeCapacity方法。
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow //如果長度超過整形的最大值彭则,則拋出異常
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? //返回整形的最大長度
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
所以鳍刷,ArrayList的最大長度是整型的最大值,超過這個值就會報OutOfMemoryError()俯抖。
public boolean add(E e)
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 數(shù)據(jù)長度自增
elementData[size++] = e;
return true;
}
在add方法中输瓜,首先會使用ensureCapacityInternal(size + 1)方法進(jìn)行數(shù)據(jù)數(shù)組擴(kuò)容,然后將待插入的元素插入到數(shù)組末尾芬萍。
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果當(dāng)前數(shù)據(jù)數(shù)組是空數(shù)組
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); //最小長度是10和所需長度的最大值
}
ensureExplicitCapacity(minCapacity); //數(shù)據(jù)數(shù)組擴(kuò)容
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; //操作數(shù)自增
if (minCapacity - elementData.length > 0)
grow(minCapacity); //數(shù)據(jù)數(shù)組擴(kuò)容
}
add方法總結(jié):
add方法中尤揣,首先會對數(shù)據(jù)數(shù)組進(jìn)行擴(kuò)容(如果現(xiàn)有的容量小于所需的容量,就擴(kuò)容)柬祠。如果第一次添加數(shù)據(jù)北戏,也就是數(shù)據(jù)數(shù)組是空數(shù)組的時候,設(shè)置最小的所需長度是10(我認(rèn)為是為了避免數(shù)據(jù)數(shù)組在剛開始的時候長度增長地過慢漫蛔,導(dǎo)致經(jīng)常擴(kuò)容嗜愈,影響效率),然后使用grow方法對數(shù)據(jù)進(jìn)行擴(kuò)容(每次增長為原來的1.5倍)莽龟。
public boolean addAll(Collection<? extends E> c)
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
首先將輸入的待插入集合轉(zhuǎn)化為數(shù)組蠕嫁,然后對數(shù)據(jù)數(shù)組擴(kuò)容,復(fù)制數(shù)組毯盈,更新size剃毒,返回。
public E set(int index, E element)
public E set(int index, E element) {
rangeCheck(index); //檢查數(shù)組是否越界
E oldValue = elementData(index);
elementData[index] = element; //設(shè)置新數(shù)據(jù)
return oldValue; //返回舊數(shù)據(jù)
}
set方法中邏輯比較簡單,首先判斷數(shù)組是否越界赘阀,如果越界拋出IndexOutOfBoundsException異常陪拘,然后將新數(shù)據(jù)設(shè)置到指定位置,返回舊數(shù)據(jù)纤壁。
public E remove(int index)
public E remove(int index) {
rangeCheck(index); //檢查數(shù)組是否越界
modCount++;
E oldValue = elementData(index); //取得需要刪除的元素
int numMoved = size - index - 1; //獲得需要移動的數(shù)據(jù)長度
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index, //移動數(shù)據(jù)左刽,填補(bǔ)空缺
numMoved);
elementData[--size] = null; // clear to let GC do its work //最后一個數(shù)據(jù)設(shè)置為null
return oldValue;
}
remove方法的邏輯同樣簡單,首先檢查index是否越界(如果越界酌媒,拋出IndexOutOfBoundsException)欠痴,然后獲得需要刪除的元素,刪除中間的一個元素后秒咨,后面的元素都需要前移一位喇辽,原來最后位置的元素設(shè)置為null,最后返回移除的元素雨席。
public E get(int index)
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
get方法邏輯比較簡單菩咨,首先檢查index是否越界,然后然后返回指定位置的數(shù)據(jù)
內(nèi)部類private class Itr implements Iterator<E>
ArrayList中有個內(nèi)部類Itr陡厘,實現(xiàn)了Iterator接口抽米,也就是我們常說的迭代器。
private class Itr implements Iterator<E> {
int cursor; // 游標(biāo)糙置,指向下一個可以返回的數(shù)據(jù)
int lastRet = -1; // 游標(biāo)云茸,指向最后一個已返回的元素
int expectedModCount = modCount; //操作次數(shù)
public boolean hasNext() { //通過比較ArrayList中的成員變量size和迭代器的游標(biāo)cursor,判斷否是還有下一個元素
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification(); //如果迭代器中的操作數(shù)和ArrayList中的操作數(shù)不相等谤饭,就拋出異常标捺。因此,我們在使用迭代器的時候揉抵,不應(yīng)該使用ArrayList自身的add,remove,set等方法亡容,否則迭代器會拋出異常!
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i]; //返回數(shù)據(jù)冤今,游標(biāo)后移闺兢,設(shè)置lastRet為剛剛返回的元素
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet); //移除上一個返回的元素
cursor = lastRet;
lastRet = -1; //重新設(shè)置lastRet為-1,所以next一次辟汰,只能remove一次列敲。
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
迭代器總結(jié):
1.迭代器封裝了對集合元素的next和remove操作,不需要了解集合底層具體的實現(xiàn)帖汞,只需要使用迭代器進(jìn)行統(tǒng)一處理
2.迭代器的remove操作是調(diào)用ArrayList的remove操作戴而,迭代器本身不對ArrayList的結(jié)構(gòu)產(chǎn)生變化。
2.迭代器內(nèi)部會保存一個操作數(shù)翩蘸,每次操作所意,迭代器都會檢查自身的操作數(shù)和ArrayList的操作數(shù)是否相等,如果不相等會拋出異常。因此扶踊,我們在使用迭代器的時候再獲取迭代器的對象泄鹏,并且在使用迭代器的過程中,不應(yīng)該使用ArrayList本身對數(shù)進(jìn)行結(jié)構(gòu)性的改變(add,remove等)秧耗。
Vector
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
Vector和ArrayList的實現(xiàn)原理大致相同备籽,都是在內(nèi)部使用數(shù)組來保存數(shù)據(jù),add和remove也都是先擴(kuò)容分井,然后對數(shù)組進(jìn)行操作车猬。最大的不一樣是Vector內(nèi)部方法都用Synchronized修飾,也就是多線程同步的尺锚。并且數(shù)組擴(kuò)容的方法也不太一樣珠闰。
首先看構(gòu)造方法
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
/**
*
*/
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
/**
*
*/
public Vector() {
this(10);
}
Vector有三個構(gòu)造方法,分別是無參瘫辩,一個參數(shù)(初始化容量)伏嗜,兩個參數(shù)(初始化容量,每次擴(kuò)容增長的容量)伐厌。前兩個構(gòu)造方法最后都是調(diào)用兩個參數(shù)的構(gòu)造方法承绸。
可以看到,如果不設(shè)置默認(rèn)的初始容量是10弧械,默認(rèn)每次擴(kuò)容增加的容量是0八酒。
private void grow(int minCapacity)
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ? //如果默認(rèn)的擴(kuò)容增量等于0,就設(shè)置新的容量為舊容量的兩倍刃唐,否則根據(jù)容量增量增加容量。
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
grow方法中界轩,會判斷現(xiàn)在的擴(kuò)容增量值是不是等于0画饥,如果等于0,則新容量是舊容量的兩倍浊猾,否則抖甘,根據(jù)擴(kuò)容增量設(shè)置新的容量。
Vector總結(jié):
1.基本原理和ArrayList相同葫慎,內(nèi)部使用數(shù)組保存數(shù)據(jù)衔彻,在需要的時候擴(kuò)容數(shù)組
2.構(gòu)造方法方法中,可以設(shè)置初始的容量和每次擴(kuò)容增加的容量偷办。默認(rèn)初始容量是10艰额,每次擴(kuò)容增加的容量是0。
3.對數(shù)據(jù)的結(jié)構(gòu)性操作的函數(shù)都使用Synchronized來修飾(如add,remove,setSize)椒涯,是線程安全的柄沮,但是多線程環(huán)境下效率比較低。
4.每次擴(kuò)容,如果現(xiàn)有設(shè)置的擴(kuò)容增量為0祖搓,則新容量為舊容量的兩倍狱意,否則,新容量為舊容量+擴(kuò)容增量拯欧。
LinkedList
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
ArrayList和Vector內(nèi)部都是用數(shù)組來存儲元素详囤,LinkedList內(nèi)部使用雙向鏈表來存儲數(shù)據(jù)(jdk1.8.0中不是循環(huán)鏈表)。下面的分析只對源碼中的思路進(jìn)行分析镐作,不對具體的鏈表操作進(jìn)行分析藏姐。
成員變量
transient int size = 0; //已存儲元素的多少
/**
* 指向鏈表中第一個元素的指針
*/
transient Node<E> first;
/**
* 指向鏈表中最后一個元素的指針
*/
transient Node<E> last;
LinkedList中保存了指向第一個元素和最后一個元素的指針。
構(gòu)造方法
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
提供了兩個構(gòu)造方法,一個沒有任何邏輯呢灶,一個傳入數(shù)據(jù)集合贷笛,調(diào)用addAll插入數(shù)據(jù)集合。
boolean addAll(int index, Collection<? extends E> c)
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index); //檢查是否越界
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index); //使用node(index)查找到指定位置的元素
pred = succ.prev;
}
for (Object o : a) { //將數(shù)據(jù)插入到鏈表中
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) { //更新last指針
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew; //修改size
modCount++; //修改操作數(shù)
return true;
}
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
在AddAll方法中首先使用node(int index)找到插入點问畅,然后將數(shù)據(jù)插入到雙向鏈表中
public boolean add(E e)
public boolean add(E e) {
linkLast(e);
return true;
}
調(diào)用linkLast將元素插入到鏈表尾部,具體怎么插入就不分析了六荒,就是雙向鏈表的插入操作护姆。
public boolean remove(Object o)
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
在remove(Object o)方法中,首先判斷o是不是null掏击,如果是卵皂,則通過for循環(huán)查到鏈表中第一個值為null的結(jié)點;否則砚亭,通過for循環(huán)找到指定結(jié)點灯变,刪除。
public E get(int index)
public E get(int index) {
checkElementIndex(index); //檢查是否越界
return node(index).item; //使用node獲取指定位置的結(jié)點
}
public E peek()
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
返回鏈表中的第一個元素
public E poll()
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
首先獲取鏈表中第一個元素捅膘,斷開其連接添祸,返回該元素。
public boolean offer(E e)
public boolean offer(E e) {
return add(e);
}
offer方法中調(diào)用add方法將元素插入到鏈表末尾寻仗,
public void push(E e)
public void push(E e) {
addFirst(e);
}
使用addFirst(e)將數(shù)據(jù)插入到鏈表開頭
public E pop()
public E pop() {
return removeFirst();
}
使用removeFirst返回鏈表的頭結(jié)點刃泌,斷開頭結(jié)點與其他結(jié)點的連接
public void clear()
public void clear() {
for (Node<E> x = first; x != null; ) { //將結(jié)點的引用指向null,使實例對象可以被GC
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null; //重置頭節(jié)點和尾結(jié)點
size = 0; //設(shè)置size為0
modCount++;
}
LinkedList總結(jié)
1.使用雙向鏈表來保存數(shù)據(jù)署尤,數(shù)據(jù)插入耙替,刪除都是通過對鏈表操作來實現(xiàn)的。
2.繼承了queue接口曹体,可以當(dāng)作隊列來使用俗扇。也提供了棧的方法,也可以當(dāng)作棧使用混坞。