Replacement for obsolete Hashtable class in Java

后端 未结 6 1662
夕颜
夕颜 2021-01-01 17:51

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 colle

相关标签:
6条回答
  • 2021-01-01 18:09

    You should use HashMap, but it is not designed for concurrent environments, where you may use ConcurrentHashMap.

    OR

    Map<K,V> myMap = Collections.synchronizedMap(/*any map instance*/);
    
    0 讨论(0)
  • 2021-01-01 18:13

    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.

    0 讨论(0)
  • 2021-01-01 18:24

    There are cases when a method outside your control requires an Hashtable. Java's own javax.management.ObjectName is such an example[1].

    When the external interface requires it you have to use Hashtable. In netbeans, you can use:

    @SupresssWarnings("UseOfObsoleteCollectionType")
    

    to suppress the warning locally.

    See

    • Java: complete list of @SuppressWarnings(...) parameters (in Netbeans)?
    • Suppress deprecated import warning in Java

    1: I wonder why they used Hashtable and not HashMap, since ObjectName is available since 1.5 and Hashtable is obsolete since 1.2

    0 讨论(0)
  • 2021-01-01 18:25

    You could probably use Hashmap:

    Map<String, Integer> mymap = new HashMap<String, Integer>();
    
    0 讨论(0)
  • 2021-01-01 18:28

    Summary

    The closest replacement is HashMap (usually via the Map interface).


    But note that Hashtable is thread-safe while HashMap is not. This is not a problem in most cases and it was intentional to make most Java collections non-thread-safe to avoid performance penalty for most common scenarios. But if you relied on Hashtable thread-safety and now need a replacement that would also be thread-safe then you have two options:

    • If you need a simple synchronization wrapper for an existing Map - use Collections.synchronizedMap(...)
    • If you need a class carefully and optimally designed for concurrent access - use ConcurrentHashMap (usually via the ConcurrentMap interface that extends the Map interface with additional concurrency features).
    0 讨论(0)
  • 2021-01-01 18:35

    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.

    0 讨论(0)
提交回复
热议问题