【码无巨细】实现一个HashMap

力扣题

这道题在力扣上有设计哈希映射。想过的话,很简单,按照哈希表的设计原理,设计一个简易的HashMap类就好。

一个简易的HashMap需要支持三个方法:

  • void put(K key, V value)
  • V get(K key)
  • void remove(K key)

为了实现哈希节点链表数组,还需要指定数组的容量capacity和设计节点类HashNode。下面是我这道题的答案【很简陋】:

class MyHashMap {

    int capacity;
    HashNode[] hashList;
    public MyHashMap() {
        this.capacity = 1000;
        this.hashList = new HashNode[this.capacity];
    }
    
    public void put(int key, int value) {
        int i = key % this.capacity;
        HashNode node = this.hashList[i];
        HashNode pre = null;
        while (node != null && node.key != key) {
            pre = node;
            node = node.next;
        }
        if (node == null) {
            if (pre == null) {
                this.hashList[i] = new HashNode(key, value);
            } else {
                pre.next = new HashNode(key, value);
            }
        } else {
            node.value = value;
        }
    }
    
    public int get(int key) {
        int i = key % this.capacity;
        HashNode node = this.hashList[i];
        while (node != null && node.key != key) {
            node = node.next;
        }
        if (node == null) {
            return -1;
        } else {
            return node.value;
        }
    }
    
    public void remove(int key) {
        int i = key % this.capacity;
        HashNode node = this.hashList[i];
        HashNode pre = null;
        while (node != null && node.key != key) {
            pre = node;
            node = node.next;
        }
        if (node != null && pre != null) {
            pre.next = node.next;
        } else if (node != null) {
            this.hashList[i] = node.next;
        }
    }
}

class HashNode {
    int key;
    int value;
    HashNode next;
    public HashNode(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

/**
 * Your MyHashMap object will be instantiated and called as such:
 * MyHashMap obj = new MyHashMap();
 * obj.put(key,value);
 * int param_2 = obj.get(key);
 * obj.remove(key);
 */

Java源码(JDK14)

实现一个简易哈希表就这么简单,但是Java源码是如何实现它的值得我们深究,下面解析一下官方代码【完整源码见官方文档,这里只挑重要的说明】:

HashMap类注释

  1. 哈希表基于Map接口实现,提供了所有可选的map操作,允许null值和null
  2. HashMapHashtable大致等同,唯一区别是前者线程不同步,且允许空值空键。
  3. HashMap是无序的,内部顺序可能随着时间变化。
  4. getput的时间复杂度是常数时间的。
  5. 如果在乎迭代性能,切记不要把初始容量设置太大,也不要把装载因子设置太小。
  6. 哈希表会在条目数超过装载因子*当前容量时发生重哈希(rehash)和扩容(至原来的2倍)。
  7. 装载因子的默认值是0.75,是时间性能和空间代价的折中。更高的值会降低空间代价,但会带来更高的查询代价。
  8. 谨记:HashMap是线程不同步的。如果多线程同时操作一个hashmap,并且至少有一个线程结构化地修改了hashmap,那么它必须被显式同步synchronize。结构化地修改具体是指插入或删除一个映射,仅仅是该表一个已有键的值并不算结构化修改。实际中最好将HashMap·封装到线程安全类中,比如Collections.synchronizedMap`是一个很好的工具。
  9. 不要在遍历HashMap的时候结构化的修改它(增加或删除)。

类声明

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

具体实现的注释前言

  1. HashMap通常是一个桶哈希,但是当桶太大时,太大的桶会转化成树,每个桶就类似于TreeMap的实现。当树变小的时候,又会退化成桶。
  2. 理想状态下,桶中节点的频率服从泊松分布(参数平均为0.5,在默认装载因子为0.75的情况下)。忽略方差的影响,每个位置发生碰撞时,那么这个位置的链表数大于等于8的概率小于1/1000000,因此,将装载因子设置为0.7~0.75(默认值)之间。

重要的成员变量

  1. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 默认初始容量,必须是2的幂次。
  2. static final int MAXIMUM_CAPACITY = 1 << 30; 最大容量,2的幂次。
  3. static final float DEFAULT_LOAD_FACTOR = 0.75f; 默认装载因子
  4. static final int TREEIFY_THRESHOLD = 8; 树化的桶大小阈值
  5. static final int UNTREEIFY_THRESHOLD = 6; 桶化的树大小阈值,仅用于resize发生时,重哈希导致某些位置的树节点变少,低于此阈值时退化成桶
  6. static final int MIN_TREEIFY_CAPACITY = 64; 最小的树化的容量阈值,。应该至少为TREEIFY_THRESHOLD的4倍。否则会引发resize和树化的冲突。

桶节点类

非常简单,都是一些Object的方法。

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;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

hash函数

HashMap中在计算键的哈希值时,使用了这个函数:

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

可以看到,他并没有直接使用key.hashCode()作为键的哈希值,而是将其hashCode()的高16位和低16位做了异或,再作为键的哈希值,这种操作叫做扰动函数

之所以在哈希时需要扰动,是因为Object.hashCode()会得到一个32位的int值,这个值在int空间中是松散的,但不见得在HashMap中是松散的(因为容量是有限的,如默认16)。在HashMap的键空键中,假设容量为16,则会只取hashCode()的低4位,这有可能会发生很严重的碰撞。但是,如果把hashCode()的高16位,拉下来和低16位做一个异或,那么就扰动了32位的信息,从而能够降低碰撞的风险。

成员变量

  1. transient Node<K,V>[] table;
  2. transient Set<Map.Entry<K,V>> entrySet;
  3. transient int size;
  4. transient int modCount; (结构化)修改计数器
  5. int threshold; 扩容阈值(容量*装载因子)
  6. final float loadFactor; 装载因子

构造器

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

其中,阈值threshold的获取是用这个函数,这个函数利用了位运算,非常高效,给定一个数cap,输出不小于cap的最小2的幂次数。

static final int tableSizeFor(int cap) {
    int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

Size()isEmpty()

返回哈希表的大小,没什么好说的

public int size() {
    return size;
}

判断是否为空

public boolean isEmpty() {
    return size == 0;
}

get方法

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; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

get方法首先要调用hash()计算key的哈希值再通过getNode方法获取key对应的节点,如果节点不为空,则返回value值。其中hash()函数做了扰动处理,对key.hashcode()的高16位和低16位做异或(不同jdk版本的实现方案不同)。

仔细看getNode的实现细节,有几点:

  1. 判定首要条件:哈希表不为空 && 哈希表的长度不为0 && 哈希表中hash对应桶的第一个元素不为空。
  2. 计算hash % (n-1)时,用位运算加速hash & (n-1)
  3. hash % (n-1)用来定位桶,hash用来比较key是否相同。
  4. 总是先检查每个桶的第一个节点first,如果是要获取的键,则返回first
  5. 节点e是目标节点的判断条件是e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))注意,需要同时满足hash相同和key相等。hash值是调用Object.hashcode()方法获取的,而key相等包括内存相等或equals()方法相等,因此,如果要实现自定义类的HashMap功能,需要设计好自定义类的hashcode()equals(),缺一不可。
  6. 如果first节点是树状节点,则执行树状搜索方法getTreeNode()

put方法

put方法调用了putVal方法来实现插入更新。需要注意的有:

  1. **put方法是有返回值的。**如果put是插入,则返回null,如果是更新,则返回旧值。
  2. resize()方法用来初始化table或扩张原table,详见下文。
  3. 如果哈希表为空,或长度为0,则调用resize()初始化。
  4. 如果hash%(n-1)对应的桶的第一个元素为空,则在这个位置上新建一个节点。
  5. 3和4均不满足,则进入到桶链表中搜索。搜索条件仍是hash值相同且key相等。如果第一个节点为目标节点,则记录之;否则如果第一个节点是树状节点,则转到树状节点插入putTreeVal;否则,对桶链表遍历,如果有满足条件的节点,则记录之,否则,插入新节点,且判断此时位置是否超过树化阈值,如果超过,则执行树化逻辑treeifyBin()
  6. 如果找到了目标节点,则执行更新逻辑。
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;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        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))))
            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);
                    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;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

至于resize()方法,无非就是新建一个更大的(2倍于原来的)哈希表,并把原来的桶链表用新的哈希函数(原来是hash%(oldCap-1),现在是hash%(newCap-1))打散到新的哈希表中。如果原来是树状的,则需要调用节点的split方法对树分割。代码稍长,不做具体分析了。

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; // 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;
}

remove方法

remove方法和put方法就大同小异了,一个是定位节点修改(或插入),一个是定位节点并删除。

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

clear()

clear()非常简单粗暴,对每一个桶,直接做null赋值。

publicvoid clear() {
    Node<K,V>[] tab;
    modCount++;
    if ((tab = table) != null && size > 0) {
        size = 0;
        for (int i = 0; i < tab.length; ++i)
            tab[i] = null;
    }
}

containsKey方法

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

调用getNode找到和key对应的节点,不为空则存在。

containsValue()

如果你把哈希表比作一个二维节点矩阵的话,哈希表存储每一个桶链表的指针,那么判断值是否存在其实是一个双层遍历,没有加速操作,复杂度是O(n^2)

public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
        for (Node<K,V> e : tab) {
            for (; e != null; e = e.next) {
                if ((v = e.value) == value ||
                    (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}

HashSet

至于HashSet的源码实现,则是完全用HashMap来代替的,插入元素时,哈希表的值设置为一个哑对象:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值