`
Veromca-源代码
  • 浏览: 40532 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Hashtable和HashMap的区别

阅读更多
Hashtable和HashMap的主要区别:

1.线程同步:
Hashtable和HashMap最大的区别就是Hashtable的方法是Synchronize的,而HashMap不是。多个线程访问Hashtable时,不需要实现同步,而HashMap需要。

2.继承不同:
Hashtable是基于陈旧的Dictionary类的;HashMap是Java 1.2引进的Map接口的一个实现。
public class Hashtable extends Dictionary implements Mappublic class HashMap  extends AbstractMap implements Map


3.是否可为空:
HashMap允许将空值作为一个表的条目的key或value。HashMap中只有一条记录可以是一个空的key,但任意数量的条目可以是空的value;而Hashtable不允许。
注意:在HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,即可以表示 HashMap中没有该键,也可以表示该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键, 而应该用containsKey()方法来判断。

4.contains方法:
HashMap去掉了Hashtable的contains方法,保留了containsValue和containsKey方法

5.两个遍历方式的内部实现上不同:
Hashtable、HashMap都使用了 Iterator。而由于历史原因,Hashtable还使用了Enumeration的方式 。

5.哈希值的使用不同:
HashTable直接使用对象的hashCode。而HashMap重新计算hash值。
HashTable:
  Entry tab[] = table;  
  int hash = key.hashCode(); //###### 注意这里  
  int index = (hash & 0x7FFFFFFF) % tab.length;  
  for (Entry 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;  
    }  
  }  


HashMap:
public V put(K key, V value) {   
  if (key == null)   
  return putForNullKey(value);  
  int hash = hash(key.hashCode());  
  int i = indexFor(hash, table.length);  
  for (Entry e = table[i]; e != null; e = e.next) {  
    Object k;  
    if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
      V oldValue = e.value;  
      e.value = value;  
      e.recordAccess(this);  
      return oldValue;  
    }  
  }  
  modCount++;  
  addEntry(hash, key, value, i);   
  return null;  
}  


5.增长方式:
HashTable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。



1
3
分享到:
评论
2 楼 gugu_abrams 2013-05-22  
liuyuhua0066 写道
冲着是Hashtable 而不是 HashTable 我就不想用这个类


现代的 JAVA 代码中都不应该使用 Hashtable,除非你的程序运行在 JAVA 1 上面。
1 楼 liuyuhua0066 2013-05-21  
冲着是Hashtable 而不是 HashTable 我就不想用这个类

相关推荐

Global site tag (gtag.js) - Google Analytics