When I tried to use the hashtable class, Netbeans gave me an error saying:
While still supported, these classes were made obsolete by the JDK1.2 collection classes, and should probably not be used in new development.
However, I can't seem to find an example online on a better replacement for Hashtable
. Any suggestions?
Ans. HashTable has been deprecated. As an alternative, ConcurrentHashMap has been provided. It uses multiple buckets to store data and hence much better performance than HashTable.
When to use HashMap and Hashtable? HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications . We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 .
This class implements a hash table, which maps keys to values. Any non- null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
The most direct replacement of a Hashtable
is a HashMap
.
One difference that could be important is that all relevant methods of Hashtable
are synchronized while they are not synchronized on HashMap
.
A better replacement for Hashtable
is HashMap
.
As for being obsolete, I have no reference to it, but the Javadoc states:
As of the Java 2 platform v1.2, this class was retrofitted to implement the
Map
interface, making it a member of the Java Collections Framework.
Hashtable
is synchronized unlike HashMap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With