Hashtable和HashMap的区别
来源:互联网 发布:淘宝上靠谱的韩代 编辑:程序博客网 时间:2024/06/08 10:14
1、两者继承的直接父类不同:Hashtable继承自Dictiionary,HashMap继承自AbstractMap,这一区别可以通过两者的源码明显地看到:
- public class HashMap<K,V>
- extends AbstractMap<K,V>
- implements Map<K,V>, Cloneable, Serializable
- public class Hashtable<K,V>
- extends Dictionary<K,V>
- implements Map<K,V>, Cloneable, java.io.Serializable
2、
Hashtable的put方法如下:
- public synchronized V put(K key, V value) {
- // Make sure the value is not null
- if (value == null) {
- throw new NullPointerException();
- }
- // Makes sure the key is not already in the 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;
- }
- }
- 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;
- }
- 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;
- }
通过比对Hashtable与HashMap的put方法,我们很容易得出这样的结论:
a、Hashtable的put方法是同步的,线程安全的;HashMap的put方法不是同步的,非线程安全的:由此可见在多线程情况下应该使用Hashtable中的put方法,反之应该使用HashMap中的put方法;由此也可以得出这样的结论Hashtable的put方法效率低于HashMap的put方法;
b、在向Hashtable中put数据时,key与value均不能为null,而在向HashMap中put数据时,key与value都可以为空;
0 0
- 什么是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的区别
- 第六周项目一深复制(3)
- 第六周项目三 人数不定的工资类
- 2015年大一下第5周项目6-复数模板类(1)复数加减乘除
- 在Ubuntu 14.04 64bit上安装配置sublime text 3(Build 3083)
- 用对象数组操作长方柱类
- Hashtable和HashMap的区别
- 第六周 程序阅读-深复制、友元、类模板(5)
- GADInterstitial备忘
- linux命令(while,shell参数的用法)
- 如何实现Android应用的静默安装
- vs2010下安装qt4、opencv遇到的问题
- 复数模板类
- 第六周项目6(2)-复数模板类
- all star官網簇新風情的converse高筒帆布鞋