HashMap Hashtable区别
2015-08-22 09:30
525 查看
2009-02-24 17:26
21310人阅读
评论(3)
收藏
举报
hashmap
null
dictionary
table
class
object
http://blog.csdn.net/java2000_net/archive/2008/06/05/2512510.aspx
我们先看2个类的定义
[java]
view plain
copy
public class Hashtable
extends Dictionary
implements Map, Cloneable, java.io.Serializable
[java]
view plain
copy
public class HashMap
extends AbstractMap
implements Map, Cloneable, Serializable
可见Hashtable 继承自 Dictiionary 而 HashMap继承自AbstractMap
Hashtable的put方法如下
[java]
view plain
copy
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方法如下
[java]
view plain
copy
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方法。
HashMap Hashtable
父类 AbstractMap Dictiionary
是否同步 否 是
k,v可否null 是 否
相关文章推荐
- Intent的各种属性问题以及IntentFilter配置问题
- aiSee3 矢量图像文本格式 示例
- 联想售后问答经典
- PostgreSQL Replication之第八章 与pgbouncer一起工作(5)
- Palindrome - POJ 3974 (最长回文子串,Manacher模板)
- Spring EL Operators example
- 全国省市数据库
- C++中delete和delete[]的区别
- 浅述IOS用到的BOOL类型
- Timer控件使用(System.Timers.Timer)
- JUnit4中的测试套件
- JAVA代理模式
- hdu-5384Danganronpa+多校训练+AC自动机
- 快速排序
- 用JUnit4进行参数化测试
- soapui的安装
- 优秀项目经理应备技能04-项目管理的原则
- 不要上传销的当
- PostgreSQL Replication之第八章 与pgbouncer一起工作(4)
- log4j