-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.json
1 lines (1 loc) · 3.41 KB
/
params.json
1
{"name":"Hashtable&HashMap的区别","tagline":"","body":"# 先总结:\r\nHashtable\r\n注意1 方法是同步的\r\n注意2 方法不允许value==null\r\n注意3 方法调用了key的hashCode方法,如果key==null,会抛出空指针异常\r\nHashMap \r\n注意1 键和值都是对象\r\n注意2 方法是非同步的(但是需要的时候可以做同步,性能比较高)\r\n注意3 方法允许key==null,但是只有一个\r\n注意4 方法并没有对value进行任何调用,所以允许为null\r\nHashtable和HashMap采用的hash/rehash算法都大概一样,所以性能不会有很大的差\r\n\r\n# 我们先看2个类的定义\r\npublic class Hashtable \r\n extends Dictionary \r\n implements Map, Cloneable, java.io.Serializable \r\n\r\npublic class HashMap \r\n extends AbstractMap \r\n implements Map, Cloneable, Serializable\r\n\r\n### 可见Hashtable 继承自 Dictiionary 而 HashMap继承自AbstractMap\r\n\r\n# Hashtable的put方法如下\r\npublic synchronized V put(K key, V value) { //###### 注意这里1 \r\n // Make sure the value is not null \r\n if (value == null) { //###### 注意这里 2 \r\n throw new NullPointerException(); \r\n } \r\n // Makes sure the key is not already in the hashtable. \r\n Entry tab[] = table; \r\n int hash = key.hashCode(); //###### 注意这里 3 \r\n int index = (hash & 0x7FFFFFFF) % tab.length; \r\n for (Entry e = tab[index]; e != null; e = e.next) { \r\n if ((e.hash == hash) && e.key.equals(key)) { \r\n V old = e.value; \r\n e.value = value; \r\n return old; \r\n } \r\n } \r\n modCount++; \r\n if (count >= threshold) { \r\n // Rehash the table if the threshold is exceeded \r\n rehash(); \r\n tab = table; \r\n index = (hash & 0x7FFFFFFF) % tab.length; \r\n } \r\n // Creates the new entry. \r\n Entry e = tab[index]; \r\n tab[index] = new Entry(hash, key, value, e); \r\n count++; \r\n return null; \r\n} \r\n\r\n# HashMap的put方法如下\r\npublic V put(K key, V value) { //###### 注意这里 1 \r\n if (key == null) //###### 注意这里 2 \r\n return putForNullKey(value); \r\n int hash = hash(key.hashCode()); \r\n int i = indexFor(hash, table.length); \r\n for (Entry e = table[i]; e != null; e = e.next) { \r\n Object k; \r\n if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { \r\n V oldValue = e.value; \r\n e.value = value; \r\n e.recordAccess(this); \r\n return oldValue; \r\n } \r\n } \r\n modCount++; \r\n addEntry(hash, key, value, i); //###### 注意这里 \r\n return null; \r\n} \r\n\r\n### 附:Hashtable容易被误解的部分\r\nhashmap 有以下这两个方法:\r\nnumbers.containsKey(a)\r\nnumbers.containsValue(value)、\r\nhashtable 有一个contain()方法:\r\n他不是判断是否存在关联的键,而是判断是否存在关键的值\r\n继承于Map接口\r\ncontains(Object value)\r\n测试此映射表中是否存在与指定值关联的键(如果此 Hashtable 将一个或多个键映射到此值,则返回 true)。\r\n判断容器中是否存在值\r\n但是contains并非和containsKey的功能一致而是和containsValue功能等同. 之所以说是等同原因是需要实现MAP中的containsValue:\r\npublic boolean containsValue(Object value) {\r\n return contains(value);\r\n}\r\n\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."}