vendredi 8 août 2014

Java - différences entre HashMap et Hashtable ? -Débordement de pile


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


Which is more efficient for non-threaded applications?




There are several differences between HashMap and Hashtable in Java:



  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

  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 HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.


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




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 ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:


ConcurrentMap.putIfAbsent(key, value)



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.




This question oftenly asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.



  1. 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).

  2. HashMap does not guarantee that the order of the map will remain constant over time.

  3. HashMap is non synchronized whereas Hashtable is synchronized.

  4. 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



  1. 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.

  2. 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.

  3. 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-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; 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.



The Map Interface





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 syncrhonisation. 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.




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 Javadocs state, is obsolete and has been replaced by the Map interface.




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.


Java Collection Matrix




As I understand it, Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap unless yoou 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.




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."


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




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, thet won't land in 1.8... :(


Are Project Coin's collection enhancements going to be in JDK8?





  • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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 Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


  • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap 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.





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.




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.




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.




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




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.




HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.




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.




HashMaps gives you freedom of synchronization and debugging is lot more easier




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




HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.




There are 5 basic differentiations with HashTable and HashMaps.



  1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

  2. 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.

  3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

  4. 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.

  5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.


Ref taken from skillgun questions




Since Hashtable in Java is a subclass of Dictionary class which is now obsolete due to the existance of Map Interface it is not used anymore. Moreover there isn't anything you can't do with a class that implements the Map Interface that you can do with a Hashtable.




My small contribution :



  1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


  2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


  3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.





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 it 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 Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.


enter image description here



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


Which is more efficient for non-threaded applications?



There are several differences between HashMap and Hashtable in Java:



  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

  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 HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.


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



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 ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:


ConcurrentMap.putIfAbsent(key, value)


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.



This question oftenly asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.



  1. 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).

  2. HashMap does not guarantee that the order of the map will remain constant over time.

  3. HashMap is non synchronized whereas Hashtable is synchronized.

  4. 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



  1. 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.

  2. 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.

  3. 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-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; 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.



The Map Interface




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 syncrhonisation. 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.



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 Javadocs state, is obsolete and has been replaced by the Map interface.



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.


Java Collection Matrix



As I understand it, Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap unless yoou 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.



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."


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



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, thet won't land in 1.8... :(


Are Project Coin's collection enhancements going to be in JDK8?




  • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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 Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


  • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap 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.




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.



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.



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.



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



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.



HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.



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.



HashMaps gives you freedom of synchronization and debugging is lot more easier



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



HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.



There are 5 basic differentiations with HashTable and HashMaps.



  1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

  2. 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.

  3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

  4. 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.

  5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.


Ref taken from skillgun questions



Since Hashtable in Java is a subclass of Dictionary class which is now obsolete due to the existance of Map Interface it is not used anymore. Moreover there isn't anything you can't do with a class that implements the Map Interface that you can do with a Hashtable.



My small contribution :



  1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


  2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


  3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.




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 it 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 Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.


enter image description here


0 commentaires:

Enregistrer un commentaire