Replacement for obsolete Hashtable class in Java

后端 未结 6 1704
夕颜
夕颜 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: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).

提交回复
热议问题