Java 集合框架

本文最后更新于 2 分钟前,文中所描述的信息可能已发生改变。

List

ArrayList 与 LinkedList 区别?

底层数据结构:

java
public class ArrayList<E> {
    // 底层数组
    transient Object[] elementData;
    private int size;

    // 默认容量
    private static final int DEFAULT_CAPACITY = 10;
}

public class LinkedList<E> {
    transient int size = 0;
    transient Node<E> first; // 头节点
    transient Node<E> last;  // 尾节点

    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;
    }
}

使用场景:

java
// 随机访问
ArrayList.get(index)  // O(1)
LinkedList.get(index) // O(n)

// 头部插入
ArrayList.add(0, element)  // O(n) - 需要移动元素
LinkedList.addFirst(element) // O(1)

// 尾部插入
ArrayList.add(element)     // O(1) - 摊销复杂度
LinkedList.addLast(element) // O(1)

// 中间插入
ArrayList.add(index, element)  // O(n)
LinkedList.add(index, element) // O(n) - 需要先定位
如何使用线程安全的 ArrayList(如 `Collections.synchronizedList` 或 `CopyOnWriteArrayList`)

HashMap

HashMap 的底层数据结构是什么?
  • JDK 7 及以前:数组 + 链表
  • JDK 8 及以后:数组 + 链表 + 红黑树

源码分析:

java
// HashMap的核心数据结构
public class HashMap<K,V> {
    // 底层数组,存储Node节点
    transient Node<K,V>[] table;

    // 链表节点
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;    // 哈希值
        final K key;       // 键
        V value;           // 值
        Node<K,V> next;    // 下一个节点
    }

    // 红黑树节点(JDK 8+)
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 父节点
        TreeNode<K,V> left;    // 左子节点
        TreeNode<K,V> right;   // 右子节点
        TreeNode<K,V> prev;    // 前一个节点
        boolean red;           // 红黑树颜色
    }
}
HashMap 是如何计算哈希值的?为什么要这样设计?

源码分析:

java
// 计算哈希值的方法
static final int hash(Object key) {
    int h;
    // 1. 获取key的hashCode
    // 2. 高16位与低16位异或,减少哈希冲突
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

// 根据哈希值计算数组索引
// 等价于 hash % table.length,但位运算更快
int index = (table.length - 1) & hash;

为什么要异或运算?

java
// 示例说明
int hashCode = "java".hashCode(); // 假设为 0x12345678
int h = hashCode >>> 16;          // 高16位:0x00001234
int finalHash = hashCode ^ h;     // 0x12345678 ^ 0x00001234 = 0x1234564C

// 这样做的好处:
// 1. 让高位也参与运算,减少冲突
// 2. 保持低位的随机性
// 3. 运算速度快
HashMap 的 put 方法执行流程?

源码分析:

java
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;

    // 1. 如果table为空,进行初始化
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;

    // 2. 计算索引,如果该位置为空,直接插入
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;

        // 3. 如果key相同,准备覆盖
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 4. 如果是红黑树节点,按树的方式插入
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        // 5. 链表处理
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    // 插入到链表尾部
                    p.next = newNode(hash, key, value, null);
                    // 链表长度>=8,转换为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1)
                        treeifyBin(tab, hash);
                    break;
                }
                // 找到相同key,准备覆盖
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }

        // 6. 覆盖旧值
        if (e != null) {
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }

    ++modCount;
    // 7. 检查是否需要扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
HashMap 什么时候扩容?扩容过程是怎样的?

扩容触发条件:

java
// 当元素个数超过阈值时扩容
// threshold = capacity * loadFactor
// 默认loadFactor = 0.75
if (++size > threshold)
    resize();

扩容过程:

java
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 (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; // 阈值也翻倍
    }

    // 创建新数组
    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 {
                    // 链表处理:分为两条链表
                    Node<K,V> loHead = null, loTail = null;
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // 根据hash值的特定位判断新位置
                        if ((e.hash & oldCap) == 0) {
                            // 位置不变
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        } else {
                            // 位置 = 原位置 + oldCap
                            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;
}
什么时候链表会转换为红黑树?为什么选择红黑树?

转换条件:

java
// 链表转红黑树的条件
static final int TREEIFY_THRESHOLD = 8;    // 链表长度>=8时转换
static final int MIN_TREEIFY_CAPACITY = 64; // 数组长度>=64时才转换

// 红黑树转链表的条件
static final int UNTREEIFY_THRESHOLD = 6;   // 红黑树节点<=6时转回链表

为什么选择红黑树?

  1. 查找效率:O(log n) vs O(n)
  2. 平衡性好:相比 AVL 树,插入删除效率更高
  3. 最坏情况下性能稳定

转换过程:

java
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 如果数组长度小于64,优先扩容而不是树化
    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);
    }
}

ConcurrentHashMap

ConcurrentHashMap 实现原理
ConcurrentHashMap 在 JDK 7 和 JDK 8 中的实现有什么不同?

JDK 7 实现(分段锁):

java
// JDK 7的分段锁实现
public class ConcurrentHashMap<K, V> {
    // 分段数组
    final Segment<K,V>[] segments;

    static final class Segment<K,V> extends ReentrantLock {
        // 每个段都是一个小的HashMap
        transient volatile HashEntry<K,V>[] table;
        transient int count;
        transient int modCount;
        transient int threshold;
        final float loadFactor;
    }
}

// 并发度 = segments.length,默认16
// 最多支持16个线程同时写入不同段

JDK 8 实现(CAS + synchronized):

java
// JDK 8的实现
public class ConcurrentHashMap<K,V> {
    // 直接使用Node数组,类似HashMap
    transient volatile Node<K,V>[] table;

    // 使用CAS操作
    private static final sun.misc.Unsafe U;

    // 对每个桶的头节点加锁
    synchronized (f) {
        // 对链表或红黑树进行操作
    }
}
ConcurrentHashMap 的 put()方法是如何实现的?

源码分析:

java
final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    int hash = spread(key.hashCode());
    int binCount = 0;

    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;

        // 1. 如果table为空,初始化
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        // 2. 如果桶为空,CAS插入
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))
                break; // 成功插入,退出循环
        }
        // 3. 如果正在扩容,帮助扩容
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        // 4. 桶不为空,加锁操作
        else {
            V oldVal = null;
            synchronized (f) { // 锁住桶的头节点
                if (tabAt(tab, i) == f) {
                    if (fh >= 0) {
                        // 链表操作
                        binCount = 1;
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) {
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            Node<K,V> pred = e;
                            if ((e = e.next) == null) {
                                pred.next = new Node<K,V>(hash, key, value, null);
                                break;
                            }
                        }
                    }
                    else if (f instanceof TreeBin) {
                        // 红黑树操作
                        Node<K,V> p;
                        binCount = 2;
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) {
                            oldVal = p.val;
                            if (!onlyIfAbsent)
                                p.val = value;
                        }
                    }
                }
            }

            if (binCount != 0) {
                // 检查是否需要树化
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }

    // 增加计数,可能触发扩容
    addCount(1L, binCount);
    return null;
}
ConcurrentHashMap 的 size()方法是如何保证准确性的?

实现原理:

java
public int size() {
    long n = sumCount();
    return ((n < 0L) ? 0 : (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)n);
}

final long sumCount() {
    CounterCell[] as = counterCells; CounterCell a;
    long sum = baseCount;
    if (as != null) {
        // 累加所有CounterCell的值
        for (int i = 0; i < as.length; ++i) {
            if ((a = as[i]) != null)
                sum += a.value;
        }
    }
    return sum;
}

// 计数器设计:baseCount + CounterCell[]
// 类似LongAdder的实现,减少竞争
private transient volatile long baseCount;
private transient volatile CounterCell[] counterCells;
ConcurrentHashMap 的扩容机制是如何实现的?

协助扩容:

java
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
    Node<K,V>[] nextTab; int sc;
    if (tab != null && (f instanceof ForwardingNode) &&
        (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
        int rs = resizeStamp(tab.length);
        while (nextTab == nextTable && table == tab &&
               (sc = sizeCtl) < 0) {
            if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                sc == rs + MAX_RESIZERS || transferIndex <= 0)
                break;
            // CAS增加扩容线程数
            if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                transfer(tab, nextTab);
                break;
            }
        }
        return nextTab;
    }
    return table;
}
材料计算常用资源