HashTable 是否维护插入顺序?
下面的代码以相同的插入顺序给出了输出。我读了 javadoc,他们甚至没有讨论插入顺序。有人可以帮助我获取正确的信息吗?
import java.util.*;
public class hash {
public static void main(String[] args) {
String str[] = { "japan",
"usa",
"japan",
"russia",
"usa",
"japan",
"japan",
"australia"};
int len = 8;
Hashtable ht = new Hashtable();
int i = 0;
while (i < len) {
String c = str[i];
System.out.println("c :" + c);
Integer intg = (Integer) ht.get(c);
if (intg == null)
ht.put(c, new Integer(1));
else
ht.put(c, new Integer(intg.intValue() + 1));
i++;
}
Enumeration k = ht.keys();
while (k.hasMoreElements()) {
String key = (String) k.nextElement();
System.out.println(key + " > " + ht.get(key));
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,事实并非如此。要保留插入顺序,请改用
java.util.LinkedHashMap
(javadoc)。此外,
HashMap
现在优于Hashtable
,因为Hashtable
具有不必要的并发开销。 (请参阅HashMap 和 Hashtable 之间的区别?。)No, it does not. To preserve insertion order, instead use
java.util.LinkedHashMap
(javadoc).Also,
HashMap
is now preferred overHashtable
, becauseHashtable
has unnecessary concurrency overhead. (See Differences between HashMap and Hashtable?.)不,事实并非如此。它只知道“哈希”顺序。如果对字符串重新排序,您会发现它们仍然以哈希表中的相同顺序出现。
no, it does not. it only knows the "hash" order. if you reorder the strings, you will find they still appear in the same order from the hashtable.
Hashtable
用于快速查找,而不是用于维护顺序。您应该研究LinkedHashMap
或其他数据结构。Hashtable
is used for fast lookup not for maintaining order. You should look intoLinkedHashMap
or other data structures.LinkedHashMap用于维护插入元素的顺序。Hashtable与HashMap类似,但它不允许空键或空值,而HashMap允许一个空键和多个空值...
LinkedHashMap is used for maintaining order of inserting elements.. Hashtable is similar to HashMap but it doesn't allow null key or value while HashMap allows one null key and several null values...
来自地图 Javadoc。
查看 Hashtable 和 HashMap 的代码也非常有用。
From Map Javadoc.
Also it's very useful to look inside the code of Hashtable and HashMap.