HashMap & HashTable

本文详细解析了哈希表的工作机制,包括哈希函数的计算、冲突解决策略以及扩容过程。通过具体代码示例,展示了如何在数组中定位元素、更新值及处理哈希碰撞。

 1 public V put(K key, V value) {
 2     K k = maskNull(key);// 如果key为null则使用缺省的Object
 3         int hash = hash(k);//将k的hashCode经过一定的计算得到新的HashCode
 4         int i = indexFor(hash, table.length);//取得HashCode在table中的位置
 5
 6       //首先在数组内根据key的HashCode找到Entry链表的第一个Entry       
 7         for (Entry<K,V> e = table[i]; e != null; e = e.next) {
 8         //如果Entry的key值HashCode相同,而且具有相同的引用或逻辑相等(equals)
 9             if (e.hash == hash && eq(k, e.key)) {
10             //将新的value放入Entry中,返回旧的value
11                 V oldValue = e.value;
12                 e.value = value;
13                 e.recordAccess(this);
14                 return oldValue;
15             }
16         }
17      
18         //修改次数加1
19         modCount++;
20       //在table的第i个位置的链表后加上一个新的Entry
21         addEntry(hash, k, value, i);
22         return null;
23 }
24
25 static boolean eq(Object x, Object y) {
26         return x == y || x.equals(y);
27     }

 

 


//hashtable
public synchronized V put(K key, V value) {
            // Make sure the value is not null
            if (value == null) {
                throw new NullPointerException();
            }

            // Makes sure the key is not already in the hashtable.
            Entry tab[] = table;
            int hash = key.hashCode();
            int index = (hash & 0x7FFFFFFF) % tab.length;
            for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
                if ((e.hash == hash) && e.key.equals(key)) {
                        V old = e.value;
                        e.value = value;
                        return old;
                }
            }

            modCount++;
            if (count >= threshold) {
                // Rehash the table if the threshold is exceeded
                rehash();

            tab = table;
            index = (hash & 0x7FFFFFFF) % tab.length;
            }

            // Creates the new entry.
            Entry<K,V> e = tab[index];
            tab[index] = new Entry<K,V>(hash, key, value, e);
            count++;
            return null;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值