Hashtable 和 HashMap的区别

来源:互联网 发布:方正字体侵权 淘宝 编辑:程序博客网 时间:2024/05/29 10:54


分类: 面试题3950人阅读评论(11)收藏举报
hashmapnulltabledictionaryclassobject

我们先看2个类的定义

[java] view plaincopyprint?
  1. public class Hashtable
  2. extends Dictionary
  3. implements Map, Cloneable, java.io.Serializable
[java] view plaincopyprint?
  1. public class HashMap
  2. extends AbstractMap
  3. implements Map, Cloneable, Serializable

可见Hashtable 继承自 Dictiionary 而 HashMap继承自AbstractMap

Hashtable的put方法如下

[java] view plaincopyprint?
  1. public synchronized V put(K key, V value) {//###### 注意这里1
  2. // Make sure the value is not null
  3. if (value == null) {//###### 注意这里 2
  4. throw new NullPointerException();
  5. }
  6. // Makes sure the key is not already in the hashtable.
  7. Entry tab[] = table;
  8. int hash = key.hashCode(); //###### 注意这里 3
  9. int index = (hash & 0x7FFFFFFF) % tab.length;
  10. for (Entry e = tab[index]; e != null; e = e.next) {
  11. if ((e.hash == hash) && e.key.equals(key)) {
  12. V old = e.value;
  13. e.value = value;
  14. return old;
  15. }
  16. }
  17. modCount++;
  18. if (count >= threshold) {
  19. // Rehash the table if the threshold is exceeded
  20. rehash();
  21. tab = table;
  22. index = (hash & 0x7FFFFFFF) % tab.length;
  23. }
  24. // Creates the new entry.
  25. Entry e = tab[index];
  26. tab[index] = new Entry(hash, key, value, e);
  27. count++;
  28. return null;
  29. }
注意1 方法是同步的
注意2 方法不允许value==null
注意3 方法调用了key的hashCode方法,如果key==null,会抛出空指针异常 HashMap的put方法如下
[java] view plaincopyprint?
  1. public V put(K key, V value) {//###### 注意这里 1
  2. if (key == null)//###### 注意这里 2
  3. return putForNullKey(value);
  4. int hash = hash(key.hashCode());
  5. int i = indexFor(hash, table.length);
  6. for (Entry e = table[i]; e != null; e = e.next) {
  7. Object k;
  8. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  9. V oldValue = e.value;
  10. e.value = value;
  11. e.recordAccess(this);
  12. return oldValue;
  13. }
  14. }
  15. modCount++;
  16. addEntry(hash, key, value, i); //###### 注意这里
  17. return null;
  18. }

注意1 方法是非同步的
注意2 方法允许key==null
注意3 方法并没有对value进行任何调用,所以允许为null

补充:
Hashtable 有一个 contains方法,容易引起误会,所以在HashMap里面已经去掉了
当然,2个类都用containsKey和containsValue方法。

结论: ashMap 在大多数情况下是优先选择的。


原创粉丝点击