HashMap底层原理

首先简单说说HashMap和HashTable的区别

  • 最主要的区别在于Hashtable是线程安全,而HashMap则非线程安全,在多线程环境下若使用HashMap需要使用Collections.synchronizedMap()方法来获取一个线程安全的集合;
  • HashMap可以使用null作为key,而Hashtable则不允许null作为key;
  • HashMap的初始容量为16,Hashtable初始容量为11;
  • HashMap是对Map接口的实现,HashTable实现了Map接口和Dictionary抽象类;
  • 两者计算hash的方法不同,Hashtable计算hash是直接使用key的hashcode对table数组的长度直接进行取模,HashMap计算hash对key的hashcode进行了二次hash,以获得更好的散列值,然后对table数组长度取摸;
  • HashMap和Hashtable的底层实现都是数组+链表结构实现。

    接下来简要分析HashMap和HashTable的底层实现原理:

    HashMap的创建初始过程
    默认填充因子

HashMap的put方法

首先看接口的put方法定义

    /**
     * Associates the specified value with the specified key in this map
     * (optional operation).  If the map previously contained a mapping for
     * the key, the old value is replaced by the specified value.  (A map
     * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
     * if {@link #containsKey(Object) m.containsKey(k)} would return
     * <tt>true</tt>.)
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>,
     *         if the implementation supports <tt>null</tt> values.)
     * @throws UnsupportedOperationException if the <tt>put</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of the specified key or value
     *         prevents it from being stored in this map
     * @throws NullPointerException if the specified key or value is null
     *         and this map does not permit null keys or values
     * @throws IllegalArgumentException if some property of the specified key
     *         or value prevents it from being stored in this map
     */
    V put(K key, V value);

HashMap会对null值key进行特殊处理,总是放到table[0]位置
put过程是先计算hash然后通过hash与table.length取摸计算index值,然后将key放到table[index]位置,当table[index]已存在其它元素时,会在table[index]位置形成一个链表,将新添加的元素放在table[index],原来的元素通过Entry的next进行链接,这样以链表形式解决hash冲突问题,当元素数量达到临界值(capactiy*factor)时,则进行扩容,是table数组长度变为table.length*2

再看HashMapput()方法的源码

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

再看HashMap的get()方法
get方法
同样当key为null时会进行特殊处理,在table[0]的链表上查找key为null的元素
get的过程是先计算hash然后通过hash与table.length取摸计算index值,然后遍历table[index]上的链表,直到找到key,然后返回

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }

最后看remove()方法
remove方法和put get类似,计算hash,计算index,然后遍历查找,将找到的元素从table[index]链表移除

    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Entry<K,V> e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }
### HashMap 底层数据结构 HashMap底层结构采用 **数组 + 链表/红黑树** 的方式实现。这种结构结合了数组的快速访问特性链表/红黑树在冲突处理中的高效性。HashMap 通过哈希函数将键(key)转换为哈希值,然后根据哈希值计算出键值对在数组中的存储位置(索引)[^2]。 - **数组**:用于存储数据的主结构,数组的每个元素被称为“桶”(bucket)。 - **链表**:当多个键值对被映射到同一个桶时,使用链表来存储这些冲突的键值对。 - **红黑树**:当某个桶中的链表长度超过一定阈值(默认为8),链表会转换为红黑树以提升查找效率[^2]。 ### HashMap 的实现原理 HashMap 的核心实现原理围绕 **哈希算法** **冲突解决机制** 展开: 1. **哈希算法**:HashMap 使用键的 `hashCode()` 方法结合扰动函数生成最终的哈希值。通过 `(n - 1) & hash` 计算出键值对的存储位置,其中 `n` 是数组的长度。这种方式确保哈希值均匀分布,减少碰撞概率[^5]。 2. **冲突解决**:当两个不同的键经过哈希计算后映射到相同的桶时,会发生哈希冲突。HashMap 使用 **拉链法** 解决冲突,即在每个桶中维护一个链表,存储所有冲突的键值对。当链表长度超过阈值时,链表会转换为红黑树以提升性能。 3. **动态扩容**:当 HashMap 中的元素数量接近其容量与负载因子(默认为0.75)的乘积时,HashMap 会自动扩容(通常是当前容量的两倍),并重新分配所有键值对到新的桶中。这个过程称为 **再哈希**(rehash)[^5]。 4. **线程安全性**:HashMap 不是线程安全的,在多线程环境下可能会导致数据不一致或死循环等问题。如果需要线程安全的实现,可以使用 `ConcurrentHashMap`[^3]。 ### 示例代码:HashMap 的基本使用 ```java import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { // 创建一个 HashMap 实例 HashMap<String, Integer> map = new HashMap<>(); // 添加键值对 map.put("Apple", 10); map.put("Banana", 20); map.put("Orange", 30); // 获取值 System.out.println("Apple: " + map.get("Apple")); // 输出 Apple: 10 // 遍历 HashMap for (String key : map.keySet()) { System.out.println(key + ": " + map.get(key)); } // 删除键值对 map.remove("Banana"); // 检查是否包含某个键 if (map.containsKey("Orange")) { System.out.println("Contains Orange"); } } } ``` ### 性能优化与使用场景 HashMap 的性能优势主要体现在 **快速的插入、查找删除操作**,其平均时间复杂度为 O(1)。这种高效性得益于哈希算法的均匀分布冲突处理机制的优化(链表转红黑树)。 在实际开发中,HashMap 被广泛用于缓存、索引、快速查找等场景。例如,在金融领域中,HashMap `ConcurrentHashMap` 被频繁用于处理高并发的数据存储访问需求[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值