正如rolfl指出的那样,Hashtable
是一个数据结构,在Collections Framework被引入之前已经存在。它可能可能被视为替代Collections.synchronizedMap
,但后者给予一些额外的灵活性。
所以一般建议可以到不在新的代码中使用Hashtable
,因为有更好的选择了。
最重要的,不管你是否使用Hashtable
与否:你不应该知道你正在使用它。特别是,你应该永远声明您的变量是一个Hashtable
,但始终是一个Map
:
// Don't do this!
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
// Do this instead (if you don't need synchronized access)
Map<Integer, Integer> ht = new HashMap<Integer, Integer>();
// Or this, if you need synchronized access:
Map<Integer, Integer> ht =
Collections.synchronizedMap(new HashMap<Integer, Integer>());
另见What does it mean to “program to an interface”?
话虽这么说,好像你不完全需要Map
或Hashtable
。从描述中,这听起来像你只是想知道某个特定的键是否包含在地图中。这可能建模以不同的方式。但最有可能的,这意味着你应该使用Set
代替Map
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
// To check whether an integer is contained in the set:
if (set.contains(42)) {
...
}
“我想整数数组工作,并且我可以使用哈希表解决问题” - ** wut?**问题:你为什么不只是使用数组? ('Integer [] arr = new Integer [capacity];') – Vogel612 2014-09-05 09:35:24
如果你只需要键而不是值,那么你使用的是错误的数据结构。你需要一个Set而不是一个Hashtable。 – janos 2014-09-05 09:55:57
如果你不担心值,那么使用'HashSet'可以存储对象 – 2014-09-05 10:00:01