【JAVA知识】HashTable和HashMap的区别,并简述Hashmap的实现原理

来源:互联网 发布:使用sci hub 知乎 编辑:程序博客网 时间:2024/05/19 20:38

1 区别:

1)继承与实现的不同

HashTable是基于陈旧的Dictionary类,完成了Map接口;HashMap是Java1.2引进的Map接口的一个实现(HashMap继承于AbstractMap,AbstractMap完成了Map接口)

2)线程安全不同

HashTable的方法是同步的,HashMap的方法是未同步的。

3)对null的处理不同

HashTable不允许null值的存在,HashMap允许null值的存在

4)增长率不同

HashTable是默认为11,增长的方式是oid*2+1
HashMap是默认16,而且增长一定是2的指数增长

5)哈希值的使用不同

HashTable是直接使用对象的哈希值,HashMap是使用处理过的哈希值

2 HashMap的实现原理(Map的实现原理)

1)HashMap的数据结构是怎么样的?

是数组+链表的数据结构。
这里写图片描述

2)put()的工作原理是怎样的?

a、先获取key对象的hashcode值进行处理

static int secondaryHash(Object key) {    int hash = key.hashCode();    hash ^= (hash >>> 20) ^ (hash >>> 12);    hash ^= (hash >>> 7) ^ (hash >>> 4);    return hash;}

b、将处理后的hashcode对table的length-1进行取余获得index即在数组中的索引位置

c、然后对该位置的Entry进行判断,若该位置为空,那么插入新的Entry。

d、若当前Entry不为空,那么根据key.equals()对该链表进行遍历,若是该key对象存在,则用新值代替旧值,否则在链表尾端插入新的Entry。

public V put(K key, V value) {    if (key == null) {    return putValueForNullKey(value);    }    int hash = secondaryHash(key);    HashMapEntry<K, V>[] tab = table;    int index = hash & (tab.length - 1);    for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {        if (e.hash == hash && key.equals(e.key)) {                preModify(e);                V oldValue = e.value;                e.value = value;                return oldValue;        }    }    // No entry for (non-null) key is present; create one    modCount++;    if (size++ > threshold) {        tab = doubleCapacity();        index = hash & (tab.length - 1);    }    addNewEntry(key, value, hash, index);    return null;}

3)get(key)的工作原理

跟put()里面的原理大致相同,根据key.hashcode()值找到相应的index,再根据key.equals()遍历该Index中的Entry链表,找到则返回对应的value,否则返回null。

public V get(Object key) {        if (key == null) {        HashMapEntry<K, V> e = entryForNullKey;        return e == null ? null : e.value;    }    int hash = key.hashCode();    hash ^= (hash >>> 20) ^ (hash >>> 12);    hash ^= (hash >>> 7) ^ (hash >>> 4);    HashMapEntry<K, V>[] tab = table;    for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];            e != null; e = e.next) {        K eKey = e.key;        if (eKey == key || (e.hash == hash && key.equals(eKey))) {            return e.value;        }    }    return null;}

3)其他方法原理也是相似的。

0 0
原创粉丝点击