[英]Replacement for obsolete Hashtable class in Java
When I tried to use the hashtable class, Netbeans gave me an error saying: 当我尝试使用哈希表类时,Netbeans给了我一个错误说:
While still supported, these classes were made obsolete by the JDK1.2 collection classes, and should probably not be used in new development.
虽然仍然受支持,但这些类已被JDK1.2集合类淘汰,并且可能不应该在新开发中使用。
However, I can't seem to find an example online on a better replacement for Hashtable
. 但是,我似乎无法在网上找到更好的替代
Hashtable
的例子。 Any suggestions? 有什么建议?
A better replacement for Hashtable
is HashMap
. 为了更好的替代
Hashtable
是HashMap
。
As for being obsolete, I have no reference to it, but the Javadoc states: 至于过时,我没有提到它,但Javadoc说:
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 .从Java 2平台v1.2开始,这个类被改进以实现
Map
接口,使其成为Java Collections Framework的成员。
Hashtable
is synchronized unlike HashMap
. 与
HashMap
不同, Hashtable
是同步的。
You should use HashMap, but it is not designed for concurrent environments, where you may use ConcurrentHashMap
. 您应该使用HashMap,但它不是为并发环境设计的,您可以使用
ConcurrentHashMap
。
OR 要么
Map<K,V> myMap = Collections.synchronizedMap(/*any map instance*/);
There are cases when a method outside your control requires an Hashtable
. 有些情况下,控件之外的方法需要
Hashtable
。 Java's own javax.management.ObjectName
is such an example [1] . Java自己的
javax.management.ObjectName
就是这样一个例子[1] 。
When the external interface requires it you have to use Hashtable
. 当外部接口需要它时,您必须使用
Hashtable
。 In netbeans, you can use: 在netbeans中,您可以使用:
@SupresssWarnings("UseOfObsoleteCollectionType")
to suppress the warning locally. 在本地抑制警告。
See 看到
1: I wonder why they used Hashtable
and not HashMap
, since ObjectName
is available since 1.5 and Hashtable
is obsolete since 1.2 1:我想知道为什么他们使用
Hashtable
而不是HashMap
,因为ObjectName
从1.5开始可用,而Hashtable
从1.2开始就已经过时了
您可以使用Hashmap:
Map<String, Integer> mymap = new HashMap<String, Integer>();
Summary 摘要
The closest replacement is HashMap (usually via the Map interface). 最接近的替换是HashMap(通常通过Map接口)。
But note that Hashtable is thread-safe while HashMap is not. 但请注意,Hashtable是线程安全的,而HashMap则不是。 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.
在大多数情况下 ,这不是问题,并且有意使大多数Java集合非线程安全,以避免大多数常见方案的性能损失。 But if you relied on Hashtable thread-safety and now need a replacement that would also be thread-safe then you have two options:
但是如果你依赖Hashtable线程安全并且现在需要一个也是线程安全的替换,那么你有两个选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.