Java HashMap 和 Hashtable 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:30:50  来源:igfitidea点击:

Differences between HashMap and Hashtable?

javacollectionshashmaphashtable

提问by dmanxiii

What are the differences between a HashMapand a Hashtablein Java?

Java中的aHashMap和a有什么区别Hashtable

Which is more efficient for non-threaded applications?

哪个对于非线程应用程序更有效?

采纳答案by Josh Brown

There are several differences between HashMapand Hashtablein Java:

JavaHashMapHashtableJava之间有几个区别:

  1. Hashtableis synchronized, whereas HashMapis not. This makes HashMapbetter for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

  2. Hashtabledoes not allow nullkeys or values. HashMapallows one nullkey and any number of nullvalues.

  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMapfor a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

  1. Hashtable同步的,而HashMap不是。这HashMap对于非线程应用程序来说更好,因为未同步的对象通常比同步的对象执行得更好。

  2. Hashtable不允许null键或值。 HashMap允许一个null键和任意数量的null值。

  3. HashMap 的子类之一是LinkedHashMap,因此如果您想要可预测的迭代顺序(默认情况下是插入顺序),您可以轻松地HashMapLinkedHashMap. 如果您使用Hashtable.

Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.

由于同步对您来说不是问题,我建议使用HashMap. 如果同步成为一个问题,您也可以查看ConcurrentHashMap.

回答by pkaeding

Based on the info here, 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.

根据这里的信息,我建议使用 HashMap。我认为最大的优点是 Java 会阻止你在迭代时修改它,除非你通过迭代器来做。

回答by izb

Hashtableis synchronized, whereas HashMapisn't. That makes Hashtableslower than Hashmap.

Hashtable是同步的,而HashMap不是。这HashtableHashmap.

For non-threaded apps, use HashMapsince they are otherwise the same in terms of functionality.

对于非线程应用程序,请使用,HashMap因为它们在功能方面是相同的。

回答by Miles D

Hashtableis similar to the HashMapand has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtablesmethods are synchronised. So in your case as you are not multi-threading, HashMapsare your best bet.

Hashtable类似于HashMap并具有类似的界面。建议您使用HashMap,除非您需要支持遗留应用程序或需要同步,因为Hashtables方法是同步的。所以在你的情况下,因为你不是多线程,HashMaps是你最好的选择。

回答by matt b

In addition to what izb said, HashMapallows null values, whereas the Hashtabledoes not.

除了 izb 所说的,HashMap允许空值,而Hashtable不允许。

Also note that Hashtableextends the Dictionaryclass, which as the Javadocsstate, is obsolete and has been replaced by the Mapinterface.

另请注意,作为Javadocs状态的Hashtable扩展Dictionary类已过时并已被接口取代。Map

回答by Tim Howland

For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.

对于线程应用程序,您通常可以使用 ConcurrentHashMap - 取决于您的性能要求。

回答by Apocalisp

HashMap: An implementation of the Mapinterface that uses hash codes to index an array. Hashtable: Hi, 1998 called. They want their collections API back.

HashMapMap使用哈希码索引数组的接口的实现。 Hashtable: 你好,1998 年打来的。他们希望恢复他们的集合 API。

Seriously though, you're better off staying away from Hashtablealtogether. 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 ConcurrentHashMapinstead.

不过说真的,你最好Hashtable完全远离。对于单线程应用程序,您不需要额外的同步开销。对于高度并发的应用程序,偏执的同步可能会导致饥饿、死锁或不必要的垃圾收集暂停。就像蒂姆豪兰指出的那样,你可以ConcurrentHashMap改用。

回答by serg10

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.

请注意,很多答案都表明 Hashtable 是同步的。 在实践中,这给你带来的影响很小。同步在访问器/修改器方法上会停止两个线程同时添加或从映射中删除,但在现实世界中,您通常需要额外的同步。

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 Hashtableor HashMap.

一个非常常见的习惯用法是“先检查再放”——即在 中查找条目,Map如果它不存在则添加它。无论您使用Hashtable或 ,这都不是原子操作HashMap

An equivalently synchronised HashMapcan be obtained by:

HashMap可以通过以下方式获得等效同步:

Collections.synchronizedMap(myMap);

But to correctly implement this logic you need additional synchronisationof the form:

但是为了正确实现这个逻辑,你需要额外的表单同步

synchronized(myMap) {
    if (!myMap.containsKey("tomato"))
        myMap.put("tomato", "red");
}

Even iterating over a Hashtable's entries (or a HashMapobtained by Collections.synchronizedMap) is not thread safe unless you also guard the Mapfrom being modified through additional synchronization.

即使迭代 aHashtable的条目(或 aHashMap获得者Collections.synchronizedMap)也不是线程安全的,除非您还Map通过额外的同步来防止被修改。

Implementations of the ConcurrentMapinterface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semanticssuch as:

ConcurrentMap接口的实现(例如ConcurrentHashMap)通过包含线程安全的检查然后操作语义来解决其中的一些问题,例如:

ConcurrentMap.putIfAbsent(key, value);

回答by aberrant80

Hashtableis considered legacy code. There's nothing about Hashtablethat can't be done using HashMapor derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.

Hashtable被视为遗留代码。没有任何事情Hashtable不能使用HashMap或 的派生来完成HashMap,因此对于新代码,我看不出有任何理由回到Hashtable.

回答by Neerja

Another key difference between hashtable and hashmap is that Iterator in the HashMap is fail-fast 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."

hashtable 和 hashmap 之间的另一个主要区别是 HashMap 中的 Iterator 是快速失败的,而 Hashtable 的枚举器不是,如果任何其他线程通过添加或删除除 Iterator 自己的 remove() 方法之外的任何元素在结构上修改映射,则抛出 ConcurrentModificationException。但这不是保证的行为,将由 JVM 尽最大努力完成。”

My source: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html

我的来源:http: //javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html