HashMap和hashtable 数据结构的区别

Hashtable和HashMap在Java面试中相当容易被问到,甚至成为了集合框架面试题中最常被考的问题,所以在参加任何Java面试之前,都不要忘了准备这一题。
我们先看2个类的定义
public class Hashtable
extends Dictionary
implements Map, Cloneable, &a href="http://lib.csdn.net/base/javase" class='replace_word' title="Java SE知识库" target='_blank' style='color:#df3434; font-weight:'&Java&/a&.io.Serializable
public class HashMap
extends AbstractMap
implements Map, Cloneable, Serializable
可见Hashtable 继承自 Dictiionary 而 HashMap继承自AbstractMap
Hashtable的put方法如下
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[] =
int hash = key.hashCode(); //###### 注意这里 3
int index = (hash & 0x7FFFFFFF) % tab.
for (Entry e = tab[index]; e != null; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.
modCount++;
if (count &= threshold) {
// Rehash the table if the threshold is exceeded
index = (hash & 0x7FFFFFFF) % tab.
// Creates the new entry.
Entry e = tab[index];
tab[index] = new Entry(hash, key, value, e);
return null;
注意1 方法是同步的注意2 方法不允许value==null注意3 方法调用了key的hashCode方法,如果key==null,会抛出空指针异常
HashMap的put方法如下
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) {
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.
e.recordAccess(this);
return oldV
modCount++;
addEntry(hash, key, value, i);
//###### 注意这里
return null;
注意1 方法是非同步的注意2 方法允许key==null注意3 方法并没有对value进行任何调用,所以允许为null
是否提供contains方法
&HashMap把Hashtable的contains方法去掉了,改成containsValue和containsKey,因为contains方法容易让人引起误解。
Hashtable则保留了contains,containsValue和containsKey三个方法,其中contains和containsValue功能相同。
我们看一下Hashtable的ContainsKey方法和ContainsValue的源码:
public boolean containsValue(Object value) {
return contains(value);
// 判断Hashtable是否包含“值(value)”
public synchronized boolean contains(Object value) {
//注意,Hashtable中的value不能是null,
// 若是null的话,抛出异常!
if (value == null) {
throw new NullPointerException();
// 从后向前遍历table数组中的元素(Entry)
// 对于每个Entry(单向链表),逐个遍历,判断节点的值是否等于value
Entry tab[] =
for (int i = tab. i-- & 0 ;) {
for (Entry&K,V& e = tab[i] ; e != null ; e = e.next) {
if (e.value.equals(value)) {
return true;
return false;
// 判断Hashtable是否包含key
public synchronized boolean containsKey(Object key) {
Entry tab[] =
/计算hash值,直接用key的hashCode代替
int hash = key.hashCode();
// 计算在数组中的索引值
int index = (hash & 0x7FFFFFFF) % tab.
// 找到“key对应的Entry(链表)”,然后在链表中找出“哈希值”和“键值”与key都相等的元素
for (Entry&K,V& e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return true;
return false;
下面我们看一下HashMap的ContainsKey方法和ContainsValue的源码:
// HashMap是否包含key
public boolean containsKey(Object key) {
return getEntry(key) != null;
// 返回“键为key”的键值对
final Entry&K,V& getEntry(Object key) {
// 获取哈希值
// HashMap将“key为null”的元素存储在table[0]位置,“key不为null”的则调用hash()计算哈希值
int hash = (key == null) ? 0 : hash(key.hashCode());
// 在“该hash值对应的链表”上查找“键值等于key”的元素
for (Entry&K,V& e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return null;
// 是否包含“值为value”的元素
public boolean containsValue(Object value) {
// 若“value为null”,则调用containsNullValue()查找
if (value == null)
return containsNullValue();
// 若“value不为null”,则查找HashMap中是否有值为value的节点。
Entry[] tab =
for (int i = 0; i & tab. i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
return false;
通过上面源码的比较,我们可以得到如下不同地方:key和value是否允许null值。
其中key和value都是对象,并且不能包含重复key,但可以包含重复的value。通过上面的ContainsKey方法和ContainsValue的源码我们可以很明显的看出:
Hashtable中,key和value都不允许出现null值。但是如果在Hashtable中有类似put(null,null)的操作,编译同样可以通过,因为key和value都是Object类型,但运行时会抛出NullPointerException异常,这是JDK的规范规定的。
HashMap中,null可以作为键,这样的键只有一个;可以有一个或多个键所对应的值为null。当get()方法返回null值时,可能是 HashMap中没有该键,也可能使该键所对应的值为null。因此,在HashMap中不能由get()方法来判断HashMap中是否存在某个键, 而应该用containsKey()方法来判断。
HashMap和Hashtable的区别
HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口。主要的区别有:线程安全性,同步(synchronization),以及速度。
1.Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map&interface的一个实现。
2.HashMap允许将null作为一个entry的key或者value,而Hashtable不允许。
3.HashMap是非synchronized,而Hashtable是synchronized,这意味着Hashtable是线程安全的,多个线程可以共享一个Hashtable;而如果没有正确的同步的话,多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。(在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap&就必须为之提供外同步(Collections.synchronizedMap))
4.另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并不是一个一定发生的行为,要看JVM。这条同样也是Enumeration和Iterator的区别。fail-fast机制如果不理解原理,可以查看这篇文章:http://www.cnblogs.com/alexlo/archive//2959233.html
5.由于HashMap非线程安全,在只有一个线程访问的情况下,效率要高于HashTable。
6.HashMap把Hashtable的contains方法去掉了,改成containsvalue和containsKey。因为contains方法容易让人引起误解。&
7.Hashtable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。
8..两者通过hash值散列到hash表的算法不一样:
,HashTbale是古老的除留余数法,直接使用hashcode
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.
而后者是强制容量为2的幂,重新根据hashcode计算hash值,在使用hash 位与 (hash表长度 – 1),也等价取膜,但更加高效,取得的位置更加分散,偶数,奇数保证了都会分散到。前者就不能保证
int hash = hash(k);
int i = indexFor(hash, table.length);
static int hash(Object x) {
  int h = x.hashCode();
  h += ~(h && 9);
  h ^= (h &&& 14);
  h += (h && 4);
  h ^= (h &&& 10);
  return
static int indexFor(int h, int length) {
  return h & (length-1);
要注意的一些术语:
&1.sychronized意味着在一次仅有一个线程能够更改Hashtable。就是说任何线程要更新Hashtable时要首先获得同步锁,其它线程要等到同步锁被释放之后才能再次获得同步锁更新Hashtable。
&2.Fail-safe和iterator迭代器相关。如果某个集合对象创建了Iterator或者ListIterator,然后其它的线程试图“结构上”更改集合对象,将会抛出ConcurrentModificationException异常。但其它线程可以通过set()方法更改集合对象是允许的,因为这并没有从“结构上”更改集合。但是假如已经从结构上进行了更改,再调用set()方法,将会抛出IllegalArgumentException异常。
&3.结构上的更改指的是删除或者插入一个元素,这样会影响到map的结构。
&代码演示部分如下:
先看个Hashtable正常输出的示例:
Hashtable table = new Hashtable();
table.put("a-key", "a-value");
table.put("b-key", "b-value");
table.put("c-key", "c-value");
输出如下:
a-key - a-value
c-key - c-value
b-key - b-value
再看个Hashtable拒绝null的示例:
table.put(null, "a-value");
运行之后异常如下:
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:399)
at com.darkmi.sandbox.HashtableTest.main(HashtableTest.java:20)
HashMap示例:
HashMap map = new HashMap();
map.put(null, "a-value");
map.put("b-key", null);
map.put("c-key", null);
b-key - null
null - a-value
c-key - null
PS:从上面的示例我们倒是可以发现Hashtable与HashMap相同的一点:无序存放。
3.两者的遍历方式大同小异,Hashtable仅仅比HashMap多一个elements方法。
Enumeration em = table.elements();
while (em.hasMoreElements()) {
String obj = (String) em.nextElement();
System.out.println(obj);
HashMap和HashTable都能通过values()方法返回一个 Collection ,然后进行遍历处理:
Collection coll = map.values();
Iterator it = coll.iterator();
while (it.hasNext()) {
String obj = (String) it.next();
System.out.println(obj);
两者也都可以通过 entrySet() 方法返回一个 Set , 然后进行遍历处理:
Set set = table.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
System.out.println(entry.getKey() + " - " + entry.getValue());
阅读(...) 评论()ConurrentHashMap和Hashtable的区别 - ImportNew
集合类是Java API的核心,但是我觉得要用好它们是一种艺术。我总结了一些个人的经验,譬如使用ArrayList能够提高性能,而不再需要过时的Vector了,等等。JDK 1.5引入了一些好用的并发集合类,它们对于大型的、要求低延迟的电子商务系统来说非常的有用。这篇文章中将会看看ConcurrentHashMap和Hashtable之间的区别。
这篇文章是以及的后续。如果你已经读过的话,那么我相信你读完本篇之后会有所收获。
为什么我们需要ConcurrentHashMap和CopyOnWriteArrayList
同步的集合类(Hashtable和Vector),同步的封装类(使用Collections.synchronizedMap()方法和Collections.synchronizedList()方法返回的对象)可以创建出线程安全的Map和List。但是有些因素使得它们不适合高并发的系统。它们仅有单个锁,对整个集合加锁,以及为了防止ConcurrentModificationException异常经常要在迭代的时候要将集合锁定一段时间,这些特性对可扩展性来说都是障碍。
ConcurrentHashMap和CopyOnWriteArrayList保留了线程安全的同时,也提供了更高的并发性。ConcurrentHashMap和CopyOnWriteArrayList并不是处处都需要用,大部分时候你只需要用到HashMap和ArrayList,它们用于应对一些普通的情况。
ConcurrentHashMap和Hashtable的区别
Hashtable和ConcurrentHashMap有什么分别呢?它们都可以用于多线程的环境,但是当Hashtable的大小增加到一定的时候,性能会急剧下降,因为迭代时需要被锁定很长的时间。因为ConcurrentHashMap引入了分割(segmentation),不论它变得多么大,仅仅需要锁定map的某个部分,而其它的线程不需要等到迭代完成才能访问map。简而言之,在迭代的过程中,ConcurrentHashMap仅仅锁定map的某个部分,而Hashtable则会锁定整个map。
原文链接:
- 译文链接: [ 转载请保留原文出处、译者和译文链接。]
关于作者:
一名在路上的程旭媛
如果A加锁之后处理业务逻辑耗时太久,这时候已经到了过期时间而自动解锁了,B又过来拿到了锁,那又该怎么...
关于ImportNew
ImportNew 专注于 Java 技术分享。于日 11:11正式上线。是的,这是一个很特别的时刻 :)
ImportNew 由两个 Java 关键字 import 和 new 组成,意指:Java 开发者学习新知识的网站。 import 可认为是学习和吸收, new 则可认为是新知识、新技术圈子和新朋友……
新浪微博:
推荐微信号
反馈建议:ImportNew.
广告与商务合作QQ:
– 好的话题、有启发的回复、值得信赖的圈子
– 写了文章?看干货?去头条!
– 为IT单身男女服务的征婚传播平台
– 优秀的工具资源导航
– 活跃 & 专业的翻译小组
– 国内外的精选博客文章
– UI,网页,交互和用户体验
– JavaScript, HTML5, CSS
– 专注Android技术分享
– 专注iOS技术分享
– 专注Java技术分享
– 专注Python技术分享
& 2017 ImportNewjava - Differences between HashMap and Hashtable? - Stack Overflow
Join Stack Overflow to learn, share knowledge, and build your career.
or sign in with
What are the differences between a
Which is more efficient for non-threaded applications?
3,45282358
17.6k92723
There are several differences between HashMap and Hashtable in Java:
is , whereas
This makes
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
does not allow null keys or values.
allows one null key and any number of null values.
One of HashMap's subclasses is , so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the
This wouldn't be as easy if you were using .
Since synchronization is not an issue for you, I'd recommend . If synchronization becomes an issue, you may also look at .
34.9k74474
Note, that a lot of the answers state that Hashtable is synchronised.
In practice this buys you very little.
The synchronization is on the accessor / mutator methods will stop two threads adding or removing from the map concurrently, but in the real world you will often need additional synchronisation.
A very common idiom is to "check then put" - i.e. look for an entry in the Map, and add it if it does not already exist.
This is not in any way an atomic operation whether you use Hashtable or HashMap.
An equivalently synchronised HashMap can be obtained by:
Collections.synchronizedMap(myMap);
But to correctly implement this logic you need additional synchronisation of the form:
synchronized(myMap) {
if (!myMap.containsKey("tomato"))
myMap.put("tomato", "red");
Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.
Implementations of the
interface (for example ) solve some of this by including thread safe check-then-act semantics such as:
ConcurrentMap.putIfAbsent(key, value);
1,47642645
18.8k115481
No one's mentioned the fact that Hashtable is not part of the Java Collections Framework - it just provides a similar API. Also, Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.
7,59243457
This question is often asked in interview to check whether candidate understands correct usage of collection classes and is aware of alternative solutions available.
The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
HashMap does not guarantee that the order of the map will remain constant over time.
HashMap is non synchronized whereas Hashtable is synchronized.
Iterator in the HashMap is
fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally
by adding or removing any element except Iterator's own remove()
method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms
Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
Structurally modification means deleting or inserting element which could effectively change the structure of map.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
Map provides Collection views instead of direct support for iteration
via Enumeration objects. Collection views greatly enhance the
expressiveness of the interface, as discussed later in this section.
Map allows you to iterate over keys, values, or key-
Hashtable does not provide the third option. Map provides a safe way
to remove entries in th Hashtable did not.
Finally, Map fixes a minor deficiency in the Hashtable interface.
Hashtable has a method called contains, which returns true if the
Hashtable contains a given value. Given its name, you'd expect this
method to return true if the Hashtable contained a given key, because
the key is the primary access mechanism for a Hashtable. The Map
interface eliminates this source of confusion by renaming the method
containsValue. Also, this improves the interface's consistency —
containsValue parallels containsKey.
13.9k776108
4,74312633
Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.
Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.
Here is the
that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.
6,81745270
17.4k26116150
HashMap: An implementation of the Map interface that uses hash codes to index an array.
Hashtable: Hi, 1998 called. They want their collections API back.
Seriously though, you're better off staying away from Hashtable altogether. For single-threaded apps, you don't need the extra overhead of synchronisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation, deadlocks, or unnecessary garbage collection pauses. Like Tim Howland pointed out, you might use ConcurrentHashMap instead.
29.7k485139
In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.
Also note that Hashtable extends the Dictionary class, which as the
state, is obsolete and has been replaced by the Map interface.
103k53236307
Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.
Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.
4,75763574
4,77252735
Another key difference between hashtable and hashmap is that Iterator in the HashMap is
while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally
by adding or removing any element except Iterator's own remove()
method. But this is not a guaranteed behavior and will be done by JVM on best effort."
My source:
Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the "latest and greatest" additions to Java spec.
For example, compare Java 5 Map iterating:
for (Elem elem : map.keys()) {
elem.doSth();
versus the old Hashtable approach:
for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
Elem elem = (Elem) en.nextElement();
elem.doSth();
In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:
Map&String,Integer& map = { "orange" : 12, "apples" : 15 };
map["apples"];
Update: No, they won't land in 1.8... :(
is synchronized, if you are using it in a single thread you can use , which is an unsynchronized version. Unsynchronized objects are often a little more performant. By the way if multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
Youn can wrap a unsynchronized map in a synchronized one using :
Map m = Collections.synchronizedMap(new HashMap(...));
HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.
The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.
HashTable and HashMap are member of the
(since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).
HashTable is considered legacy code, the documentation advise to use
in place of Hashtable if a thread-safe highly-concurrent implementation is desired.
HashMap doesn't guarantee the order in which elements are returned. For HashTable I guess it's the same but I'm not entirely sure, I don't find ressource that clearly state that.
14.7k93877
HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the Hashtable implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.
Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a "manual drive" car where you have better control over the hashing and the HashMap as the "automatic drive" counterpart that will generally perform well.
4,71873679
Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.
For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.
21.5k2893153
Differences between HashMap and Hashtable in Java:
1) Thread Safe
HashTable is internally synchronized.
Therefore, it is very much safe to use HashTable in multi threaded applications.
Where as HashMap is not internally synchronized.
Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization.
You can externally synchronize HashMap using Collections.synchronizedMap() method.
2) Inherited From
Though both HashMap and HashTable implement Map interface, but they extend two different classes.
HashMap extends AbstractMap class where as HashTable extends Dictionary class which is the legacy class in java.
3) Null Keys And Null Values
HashMap allows maximum one null key and any number of null values.
Where as HashTable doesn’t allow even a single null key and null value.
4) Traversal
HashMap returns only Iterators which are used to traverse over the elements of HashMap.
HashTable returns Iterator as well as Enumeration which can be used to traverse over the elements of HashTable.
5) Fail-Fast Vs Fail-Safe
Iterator returned by HashMap are fail-fast in nature i.e they throw ConcurrentModificationException if the HashMap is modified
after the creation of Iterator other than iterator’s own remove() method.
On the other hand, Enumeration returned by the HashTable are fail-safe in nature i.e they don’t throw any exceptions if the HashTable is modified after the creation of Enumeration.
6) Performance
As HashTable is internally synchronized, this makes HashTable slightly slower than the HashMap.
7) Legacy Class
HashTable is a legacy class.
It is almost considered as due for deprecation.
Since JDK 1.5, ConcurrentHashMap is considered as better option than the HashTable.
8) Member Of Java Collection Framework
HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK 1.2.
But, HashTable was there before JDK 1.2. From JDK 1.2, it has been made to implement Map interface, making it a member of collection framework.
Which is more efficient for non-threaded applications?
Hashtable is synchronized, whereas HashMap is not.
This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
Based on the info , I'd recommend going with HashMap.
I think the biggest advantage is that Java will prevent you from modifying it while you are iterating over it, unless you do it through the iterator.
21.9k2277128
For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.
6,49532142
There is many good answer already posted. I'm adding few new points and summarizing it.
HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
2) HashMap allows one null key and multiple null values.
3) HashMap is a new class introduced in JDK 1.2.
4) HashMap is fast.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(HashMap);
6) HashMap is traversed by Iterator.
7) Iterator in HashMap is fail-fast.
8) HashMap inherits AbstractMap class.
1) Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) Hashtable doesn't allow any null key or value.
3) Hashtable is a legacy class.
4) Hashtable is slow.
5) Hashtable is internally synchronized and can't be unsynchronized.
6) Hashtable is traversed by Enumerator and Iterator.
7) Enumerator in Hashtable is not fail-fast.
8) Hashtable inherits Dictionary class.
Further reading
2,57112430
Difference between HashMap and HashTable / HashMap vs HashTable
Synchronization or Thread Safe :
This is the most important difference between two . HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
When to use HashMap ?
answer is if your application do not require any multi-threading task, in other words hashmap is better for non-threading applications. HashTable should be used in multithreading applications.
Null keys and null values :
Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
Iterating the values:
Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.
Fail-fast iterator
: The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.
According to Oracle Docs,
if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method , then the iterator will throw ConcurrentModification Exception.
Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.We have already explained the difference between iterator and enumeration.
Performance :
Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized
object like Hashtable in single threaded environment.
Superclass and Legacy :
Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map"
abstract data type.
2,99711118
Apart from the differences already mentioned, it should be noted that since Java 8, HashMap dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree), so that even if high hash collisions exist, the worst case when searching is
O(log(n)) for HashMap Vs O(n) in Hashtable.
*The aforementioned improvement has not been applied to Hashtable yet, but only to HashMap, LinkedHashMap, and ConcurrentHashMap.
FYI, currently,
TREEIFY_THRESHOLD = 8 : if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.
UNTREEIFY_THRESHOLD = 6 : when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.
2,72021319
There are 5 basic differentiations with HashTable and HashMaps.
Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.
In Hashtable there is a function contains(), which is very confusing to use. Because the meaning of contains is slightly deviating. Whether it means contains key or contains
value? tough to understand. Same thing in Maps we have ContainsKey() and ContainsValue() functions, which are very easy to understand.
In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.
HashTables are by default synchronized, so it can be used with multiple threads easily. Where as HashMaps are not synchronized by default, so can be used with only single thread.
But you can still convert HashMap to synchronized by using Collections util class's synchronizedMap(Map m) function.
HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.
158k40356525
1.Hashmap and HashTable both store key and value.
2.Hashmap can store one key as null. Hashtable can't store null.
3.HashMap is not synchronized but Hashtable is synchronized.
4.HashMap can be synchronized with Collection.SyncronizedMap(map)
Map hashmap = new HashMap();
Map map = Collections.SyncronizedMap(hashmap);
33.8k16109139
My small contribution :
First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe
while Hashtable is a thread-safe collection.
Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.
Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.
33.8k16109139
6,953144765
is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with . If you don't require thread safety, use
which isn't
but faster and uses less memory.
1)Hashtable is synchronized whereas hashmap is not.
2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.
3)HashMap permits null values in it, while Hashtable doesn't.
1,85821621
HashMap:- It is a class available inside java.util package and it is used to store the element in key and value format.
Hashtable:-It is a legacy class which is being recognized inside collection framework
Hashtable:
Hashtable is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.
import java.util.M
import java.util.H
public class TestClass {
public static void main(String args[ ]) {
Map&Integer,String& states= new Hashtable&Integer,String&();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null);
//will throw NullPointerEcxeption at runtime
System.out.println(states.get(1));
System.out.println(states.get(2));
System.out.println(states.get(3));
HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.
import java.util.HashM
import java.util.M
public class TestClass {
public static void main(String args[ ]) {
Map&Integer,String& states = new HashMap&Integer,String&();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null);
states.put(null,"UK");
System.out.println(states.get(1));
System.out.println(states.get(2));
System.out.println(states.get(3));
40.7k1089103
HashMaps gives you freedom of synchronization and debugging is lot more easier
user1506047
HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.
HashMap is a class
used to store the element in key and value format.it is not thread safe.
because it is not synchronized .where as Hashtable is synchronized.Hashmap permits null but hastable doesn't permit null.
protected by ♦
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10
on this site (the ).
Would you like to answer one of these
Not the answer you're looking for?
Browse other questions tagged
The week's top questions and answers
Important community announcements
Questions that need answers
By subscribing, you agree to the
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 equals和==的区别 的文章

 

随机推荐