1、不同点:
(1)、Hashtable书写不规范,t是小写(当然这不是重点,哈哈),
(2)、Hashtable继承自Dictionary,而HashMap继承自AbstractMap。
(3)、Hashtable是JDK1.0时就有的,而HashMap是在JKD1.2时才出现的。
可看两个类的定义:
* @since JDK1.0
*/
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable { * @since 1.2
*/
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{2、Hashtable的put方法中key和value都不允许为null,而HashMap的put方法中key和value允许为null。
3、Hashtable是线程安全的,效率低,HashMap是线程不安全的,效率高。
以上两点可通过如下Hashtable和HashMap的put方法的源码得知:
Hashtable的put方法:
public synchronized V put(K key, V value) { //1、方法是同步的
// Make sure the value is not null
if (value == null) { //2、value不能为null
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = hash(key);//3、看如下hash(key);
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;
}
}
---------------------------------------------------------------------
private int hash(Object k) {
// hashSeed will be zero if alternative hashing is disabled.
return hashSeed ^ k.hashCode();//key也是不能为null的,不然会抛空指针异常。
}HashMap的put方法:
public V put(K key, V value) { //1、方法是不同步的
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);//2、key可以为null
int hash = hash(key);
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++;
//3、方法并没有对value进行任何调用,所以value可以为null
addEntry(hash, key, value, i);
return null;4、Hashtable 有一个 contains方法,容易引起误会,所以在HashMap里面已经去掉了。当然,2个类都有containsKey和containsValue方法。
==========================================================================================
总结:
1、不同点:
(1)、Hashtable书写不规范,t是小写(当然这不是重点),
(2)、Hashtable继承自Dictionary,而HashMap继承自AbstractMap。
(3)、Hashtable是JDK1.0时就有的,而HashMap是在JKD1.2时才出现的。
2、Hashtable的put方法中key和value都不允许为null,而HashMap的put方法中key和value允许为null。
3、Hashtable是线程安全的,效率低,HashMap是线程不安全的,效率高。
4、Hashtable 有一个 contains方法,容易引起误会,所以在HashMap里面已经去掉了。当然,2个类都有containsKey和containsValue方法。
本文出自 “Simple Life” 博客,请务必保留此出处http://simplelife.blog.51cto.com/9954761/1860192
原文地址:http://simplelife.blog.51cto.com/9954761/1860192