Java集合實作了常用資料結構,是開發中最常用的功能之一。
Java集合主要的功能由三個接口:List、Set、Queue以及Collection組成。
常見接口:
- List : 清單,順序存儲,可重複
- Set :集合,與數學中的集合有同樣的特性:元素不能重複
- Queue:隊列
- Collection:所有Java集合的接口,定義了“集合”的常用接口
結構結構
常用集合
- ArrayList 一種可以動态增長或縮減的索引集合,底層通過
數組實作,預設容量為10,在使用是如果确定倉儲的資料容量應盡量為其初始化以避免動态擴容時的拷貝開銷Ojbect[]
- LinkedList 高效插入删除的有序序列,是雙向連結清單,使用node節點存儲資料;它又實作了雙向隊列
- ArrayDeque 用循環數組實作的雙端隊列
- HashSet 一種沒有元素的無序集合
- TreeSet 有序的集合
- LinkedHashSet 能記錄插入順序的集合
- PriorityQueue 優先隊列
- HashMap 存儲鍵/值關系資料
- TreeMap 能根據鍵的值排序的鍵/值關系資料資料
- LinkedHashMap 可以鍵/值記錄添加順序
Java集合架構結構
如何選用這些資料結構
通常選用基于我們需要處理的資料的特點以及集合的特點來确定的。
如果隻是簡單存儲一組資料,如幾個使用者的資訊,這時選用ArrayList是比較合适的,如果資料頻繁添加、删除那選用LinkedList是比較合适的。
如果想存儲一組資料且不希望重複,那選用Set集合合适的。
如果希望添加插入的資料能夠有順序,那選擇TreeSet是比較合适的,當然TreeMap也可以。
使用
ArrayList
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ArrayListTest {
@Test
public void test() throws Exception {
ArrayList<Integer> list = new ArrayList<>();
// 更推薦使用面向接口的使用方式,友善以後切換
//List<Integer> list = new ArrayList<>();
list.add(3);
list.add(2);
list.add(1);
// for列印
for (Integer e : list) {
System.out.println(e);
}
// 排序 小->大
Collections.sort(list);
System.out.println(list); // 列印
// 排序 大->小
List<Integer> list2 = Arrays.asList(2,3,5);
Collections.sort(list2,(a,b)->b-a);
// 排序 大->小
list2.sort((a, b) -> b - a); // 功能同上
System.out.println(list2);
}
}
// 輸出
3
2
1
[1, 2, 3]
[5, 3, 2]
Set
import org.junit.Test;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class SetTest {
static class User {
String name;
int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return Objects.hashCode(this.name);
}
// 邏輯根據名字判斷User是否相同
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj instanceof User) {
User u = (User) obj;
return this.name != null
? this.name.equals(u.name)
: u.name == null;
}
return false;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Test
public void test() throws Exception {
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.add(3);
System.out.println(set);
// 添加重複的人
Set<User> users = new HashSet<>();
users.add(new User("張三",18));
// 重複,不進行添加
users.add(new User("張三",19));
users.add(new User("李四",20));
for (User u : users) {
System.out.println(u);
}
}
}
// 輸出
[1, 2, 3]
User{name='null', age=18}
User{name='李四', age=20}
HashMap
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
@Test
public void test() throws Exception {
HashMap<String,String> map = new HashMap<>();
map.put("張三","110");
map.put("李四","119");
map.put("王二","120");
// 鍵重複,更新原有的
map.put("王二","139");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey()+" ---> "+entry.getValue());
}
}
}
// 列印
李四 ---> 119
張三 ---> 110
王二 ---> 139
源碼分析
基于JDK1.8。
不重要的方法已經清除,保留的方法已經注釋。
ArrayList
package java.util;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import sun.misc.SharedSecrets;
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
/**
* 預設容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 空數組,用作初始化
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 共享空數組
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 存放資料數
*/
transient Object[] elementData; // non-private to simplify nested class access
/**
* 數組大小,elementData存儲元素數量同步
*/
private int size;
/**
* 構造器
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else { // inittialCapatity < 0 抛出異常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* 構造器
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
* 構造器
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray(); // c!= null
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class)
// 不是一個一個取值指派給elementData,copyOf使用System.arrayCopy(), arrayCopy使用本地方法(JNI)效率很高
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
/**
* 去掉數組(elementData)中不存資料的部分
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
/**
* 調整List大小,可以擴容和縮容,縮容時最小容量不小于10
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
? 0
: DEFAULT_CAPACITY;
// 小于最小容量不調整,是以最小容量不會小于10
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
/**
* 最大容量
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 動态擴容方法, 容量為之前的1.5倍 oldCapacity + (oldCapacity >> 1)
*/
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* 擷取list大小
*/
public int size() {
return size;
}
/**
* 判斷list是否為空
*/
public boolean isEmpty() {
return size == 0;
}
// 每次取出元素操作時都會調用此方法對Ojbect數組原型進行類型轉換
E elementData(int index) {
return (E) elementData[index];
}
/**
* 擷取元素
*/
public E get(int index) {
rangeCheck(index); // 檢查是否越界
return elementData(index);
}
/**
* 添加元素
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
/**
* 删除
*/
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;
return oldValue;
}
/**
* 兩個list做差集
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
/**
* 批量移除
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
// 調用回調 (e)->{ //操作e }
action.accept(elementData[i]);
}
// 周遊過程禁止修改list!
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* 移除步驟:
* 1. 标記移除
* 2. 修改線程
* 3. 移動元素
* 4. 清除尾部元素
*/
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
// 标記元素
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
// 移動元素 例如: [1][2][3] size=2 移動後 [1][3][3]
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
// 清除尾部元素
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
// 更新size
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
}
HashMap
底層資料結構:數組連結清單+紅黑樹
預設的容量為:16(1<<4)
擴容的條件:size>=容量*加載因子
擴容大小:舊容量2倍(newCap = oldCap << 1)
樹化(terrify)的條件
- 容量長度大于等于64
- 連結清單成都大于8
樹化的過程
- 把普通節點轉換為TreeNode
- 調用treeify進行樹化
- 調整節點
- 左旋右旋
put導緻死循環的原因。在JDK1.7中插入元素使用頭插法,插入的時候不需要周遊哈希桶,在多線程下這樣可能形成循環連結清單。JDK8采用尾插法,循環找到最後一個節點,然後在最後一個節點插入元素。
存儲結構
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
/**
* 預設容量16
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量,1 << 30 = 1073741824
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 預設加載因子,是決定存儲容量擴容的關鍵名額,計算公式: size/總容量
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 小于這個值無法使用紅黑樹,HashMap容量不推薦為奇數,比這個數小後樹退化為數組
* 紅黑樹擴充時也參考這個屬性
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 容量小于這個值紅黑樹将退化為數組存儲
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 将數組轉化為紅黑樹推薦的容量
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 使用數組存儲的資料結構,node節點
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
/**
* 計算對象的hash值,是hash code配置設定更均勻,減少沖突幾率
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 計算2的幂次方表容量
* 也就是說表容量隻能為: ... 4 8 16 32 64 128 256 ... 1024 ... 1073741824
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/* ---------------- Fields -------------- */
/**
* 數組存儲結構,預設第一次使用時會配置設定空間
*/
transient Node<K,V>[] table;
/**
* 鍵值對數量
*/
transient int size;
/**
* 對table修改的次數,調整table時改變 —— rehash、remove、add等操作
* 用來判斷在讀取操作過程中是否出現table修改
*/
transient int modCount;
/**
* 擴容時的臨界值,計算為 capacity*loadFactor
*/
int threshold;
/**
* 加載因子, 預設0.75
*/
final float loadFactor;
/* ---------------- Public operations -------------- */
/**
* 預設構造函數,table容量為16
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // 0.75
}
/**
* 擷取存儲鍵值對數量
*/
public int size() {
return size;
}
/**
* 判空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 通過key擷取value
* 下面的getNode是核心方法。
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* 擷取操作
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n; // n table長度
K k;
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
// 根據存儲結構來擷取資料
// 紅黑樹,調用getTreeNode
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 周遊連結清單
do {
//較key查詢value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
/**
* 添加資料
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table未初始化會執行
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 存放值
if ((p = tab[i = (n - 1) & hash]) == null)// 判斷通過hash計算出的位置是否有值
// 沒有就在該位置(i)建立一個node并指派
tab[i] = newNode(hash, key, value, null);
else {// 這裡時計算出的位置有值存在
Node<K,V> e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
// 判斷hash值、key相同,認為
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 周遊哈希桶
for (int binCount = 0; ; ++binCount) {
// 周遊到桶最後一個元素(連結清單最後一個元素)
if ((e = p.next) == null) {
// 添加元素
p.next = newNode(hash, key, value, null);
// 判斷,隻有哈希桶至少為8個的時候才進行樹化,TREEIFY_THRESHOLD預設為8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 判斷鍵值是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 下一個元素
p = e;
}
}
// 更新值
if (e != null) { // existing mapping for key —— 存在鍵的映射
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 超出HashMap存放元素的門檻值threshold = capacity * loadFactor(0.75)
if (++size > threshold)
// 調整Hash存在空間大小
resize();
afterNodeInsertion(evict);
return null;
}
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 舊容量,為哈希桶長度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 這個if用來保證HashMap門檻值threshold不超限
if (oldCap > 0) {
// 判斷是否超出最大容量,到最大容量不再擴容
if (oldCap >= MAXIMUM_CAPACITY) {
// 門檻值設定整型最大值
threshold = Integer.MAX_VALUE;
// 傳回并不再調整大小
return oldTab;
}
// 在容量範圍内
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold 為原先的兩倍
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 計算加載因子,設定新的門檻值 門檻值=新容量*加載因子
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 新的哈希桶
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 将舊桶的元素更新到新桶
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
// 舊桶中的值移動到新桶
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 執行紅黑樹操作
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order - 翻轉順序
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
/**
* 樹化方法
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
/* ------------------------------------------------------------ */
// Tree bins
/**
* 紅黑樹
*
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
}
}
(完)
文章同步我的個人部落格:https://www.elltor.com/archives/106.html