HashMap和Hashtable的区别

来源:互联网 发布:淘宝设计教程 编辑:程序博客网 时间:2024/06/05 02:39

它们都是Map接口的类,实现了将唯一键映射到特定的值上。

HashMap类没有分类或者排序,它允许一个null键和多个null值

Hashtable类似于HashMap,但是不允许null键和null值。它也比HashMap慢,因为它是同步的。

Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map Interface的一个实现。

HashMap允许将null作为一个entry的key或者value,而Hashtable不允许,还有就是,HashMap把Hashtable的contains方法去掉了,改成containsvalue(Return true if this map maps one or more keys to the specified value)(如果相对应的map对应制定value有多个key,则返回值为真)和constainsKey(Return true if this map constains a mapping for the specified key)(如果对制定的key,map存在相应的映射则返回值为真)。因为constains(Tests if some key maps into the specified value in this hashtable)(检测哈希表中是否有value和key存在对应)方法容易让人引起误解。

两者间最大的不同是,Hashtable的方法是Synchronize的,而HashMap不是;在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMaori就必须为只提供外同步。

Hashtable和HashMap采用的hash/rehash算法类似,所以性能不会有很大的差异。


上述内容摘自《JAVA程序员面试宝典》第四版。

原创粉丝点击