This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Q: What is the difference between HashMap and a Hashtable in Java?

What is the difference between HashMap and a Hashtable in Java?

Which works better for non-threaded applications?

Answer:

There are several differences between HashMap and a Hashtable in Java:

  1. Hashtable is synchronous. This makes non-threaded applications more suitable because unsynchronized objects generally perform better than synchronized objects (HashMapHashMap).

  2. A Hashtable does not allow a null key or value. If we put a value that is null into a Map, we will throw a null pointer exception:

  3. One of the subclasses of HashMap is LinkedHashMap, so if you want a predictable iteration order (insertion order by default), you can easily replace the iteration order with LinkedHashMap. If you’re using Hashtable, it’s not that easy, you need to iterate over compare.

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>
{
Copy the code
  1. ConcurrentHashMap is recommended to support both thread safety and performance

Answer:

Note that many of the answer states are hashed synchronously. In fact, it’s of no use to you. Synchronization is the accessor/mutant method that will stop both threads being added or removed from the map at the same time, but in the real world you often need additional synchronization.

A very common idiom is “check and drop” — that is, look for an entry among entries and add it if it doesn’t exist. This is by no means an atomic operation, either you use or. MapHashtableHashMap

By: HashMap

Collections.synchronizedMap(myMap);
Copy the code

But to implement this logic correctly, you need to perform additional synchronization on the form:

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

It is not safe to reread even the “entry” (or the entry obtained by) unless you also prevent changes through additional synchronization.

HashtableHashMapCollections.synchronizedMapMap
Copy the code

Implementations of concurrent Map interfaces (such as concurrent HashMap) address some of these issues by including thread-safety checks followed by action semantics, such as:

ConcurrentMap.putIfAbsent(key, value);
Copy the code

The article translated from stackoverflow.com/questions/2…

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️