本文會從源碼(JDK 1.8)的角度來分析如下幾個Java中經常使用的數據結構,主要會分析原理與實現,以及每一個數據結構所支持的經常使用操做的複雜度。node
ArrayList是經過一串Object數組來存儲數據。全部操做都是經過數組索引來進行。
LinkedList是經過雙向鏈表結構來存儲數據,對數據的操做都是經過索引進行。
HashMap<K, V>是基於哈希表這個數據結構的Map接口具體實現,容許null鍵和null值(最多隻容許一個key爲null,但容許多個value爲null)。這個類與HashTable近似等價,區別在於HashMap不是線程安全的而且容許null鍵和null值。因爲基於哈希表實現,因此HashMap內部的元素是無序的,相似於咱們使用的「字典」。HashMap是採用數組+鏈表實現的,非線程安全。
複製代碼
ArrayList:數組
/** * Appends the specified element to the end of this list.
* * @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
複製代碼
LinkedList:安全
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/** * Inserts element e before non-null Node succ. */
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
根據源碼能夠看出,ArrayList的增刪操做調用了System.arrayCopy,是將數組平移獲得,這樣處理內存消耗和速度都很大,而LinkedList是經過鏈表指針進行的增刪操做,所以LinkedList的效率更高。
而對於查詢方法,,ArrayList是經過下標直接獲取返回,而LinkedList須要移動指針來查詢,對於數據量大狀況來講,ArrayList比較適合查詢。
複製代碼
HashMap是基於拉鍊法處理碰撞的散列表的實現,一個存儲整型元素的HashMap的內部存儲結構以下圖所示:數據結構
咱們能夠看到,HashMap是採用數組+鏈表實現的,在JDK 1.8中,對HashMap作了進一步優化,引入了紅黑樹。當鏈表的長度大於8時,就會使用紅黑樹來代替鏈表。app