Hashtable 和 HashMap的区别
来源:互联网 发布:科比06赛季场均数据 编辑:程序博客网 时间:2024/04/28 04:50
我们先看2个类的定义
public class Hashtable extends Dictionary implements Map, Cloneable, java.io.Serializable
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable
可见Hashtable 继承自 Dictiionary 而 HashMap继承自AbstractMap
Hashtable的put方法如下
public synchronized V put(K key, V value) { //###### 注意这里1 // Make sure the value is not null if (value == null) { //###### 注意这里 2 throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key.hashCode(); //###### 注意这里 3 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; } } 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 e = tab[index]; tab[index] = new Entry(hash, key, value, e); count++; return null; }注意1 方法是同步的
注意2 方法不允许value==null
注意3 方法调用了key的hashCode方法,如果key==null,会抛出空指针异常 HashMap的put方法如下
public V put(K key, V value) { //###### 注意这里 1 if (key == null) //###### 注意这里 2 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; }
注意1 方法是非同步的
注意2 方法允许key==null
注意3 方法并没有对value进行任何调用,所以允许为null
补充:
Hashtable 有一个 contains方法,容易引起误会,所以在HashMap里面已经去掉了
当然,2个类都用containsKey和containsValue方法。
结论: ashMap 在大多数情况下是优先选择的。
<script type="text/javascript"><!--google_ad_client = "pub-2908059660288034";/* 728x90,首页中间 创建于 08-8-14 */google_ad_slot = "5903610560";google_ad_width = 728;google_ad_height = 90;//--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
- 什么是HashTable?HashMap和HashTable的区别
- HashTable和HashMap的区别
- HashTable和HashMap的区别
- Hashtable和HashMap的区别
- HashTable和HashMap的区别
- Hashtable和HashMap的区别
- Hashtable和HashMap的区别
- HashTable和HashMap的区别
- HashTable和HashMap的区别
- Hashtable和HashMap的区别
- Hashtable和HashMap的区别
- Hashtable和HashMap的区别
- HashTable和HashMap的区别
- HashMap和Hashtable的区别
- hashtable和hashmap的区别
- hashtable 和 hashmap的区别
- HashTable和HashMap的区别
- HashTable和HashMap的区别
- Sky.Lanshen的个人成长经历
- 开始。
- Color对象的比较
- String、StringBuffer、StringBuilder的性能测试
- 求教高手,关于指针的
- Hashtable 和 HashMap的区别
- 经典编程题,大家一起做
- python最简单的测量时间方法
- 临睡前的8大护肤招
- 花钱是一种风度
- Visual C++ 2005 中的命名返回值优化
- php用Smarty模板生成html文件
- 读取xml 文件
- 30岁而立之前成功12条黄金法则