HashMap & HashTable

来源:互联网 发布:gre背单词软件 编辑:程序博客网 时间:2024/06/04 20:09

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

原创粉丝点击