HashMap和Hashtable的区别
来源:互联网 发布:java程序员招聘要求 编辑:程序博客网 时间:2024/06/08 06:40
1、HashMap的很多方法都不是线程安全的。Hashtable中大部分的方法都是线程安全的。而且HashMap中允许key为null,而Hashtable不允许。
也就是说:大部分(例如Hashtable里面的containsValue方法就不是synchronized)Hashtable的方法是Synchronize的,而HashMap不是,在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap 就必须为之提供外同步。
这些都可以从源码中看出来,
HashMap中的put方法:
public V put(K key, V value) {//这个API的设计的时候为什么要有返回值????有点不知道为什么。。。而且按照驼峰命名法,Hashtable的拼写规则应该是HashTable if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> 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中的put方法
public synchronized V put(K key, V value) {// Make sure the value is not nullif (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<K,V> 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; }}
2、二者都实现了Map接口。但Hashtable继承与Dictionary这个类,而HashMap继承与AbstractMap这个抽象类(其实AbstractMap也还是实现了Map接口的)。代码如下:
Hashtable的部分源码如下:
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable { /**
HashMap的部分源码如下:
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{
AbstractMap部分源码如下:
public abstract class AbstractMap<K,V> implements Map<K,V> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractMap() { }
3、有人说,HashMap把Hashtable的contains方法去掉了,改成containsvalue和containsKey。(其实,hashtable中也是有containsKey和containsValue这两个方法的,至少我看的版本的源码中是包含这两个方法的。只是hashTable中的ContainsValue内部还是调用他自己的contains()方法
4 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的区别
- presentModalViewController和dismissModalViewControllerAnimated的使用总结
- Linux(centos)安装总结
- ANDROID内存优化(大汇总——中)
- 面试题29 数组中出现次数超过一半的数字
- spring 事务五种方式
- HashMap和Hashtable的区别
- web中出现的中文乱码问题总结
- VDSM(6)调试错误集
- 线索二叉树
- Longest Increasing Subsequence(LIS)
- lnmp一键安装方法
- Eclipse插件安装方式
- Fedora 博通无线网卡 linux 驱动
- 数据存储与输出输入