在我的项目中,我使用了一些属性文件。我注意到 Properties.propertyNames() 的奇怪行为,它返回一个枚举,该枚举是相反的顺序。我做了一个测试: 文件内容为:
TT.1=Development
TT.2=Application Setup / Release
TT.3=Project Management
TT.4=Meetings and Discussions
代码是:
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String value = properties.getProperty(key);
System.out.println(key + " " + value);
}
输出是:
TT.4 Application Setup / Release
TT.3 Development
TT.2 Meetings and Discussions
TT.1 Project Management
谁能说说背后的原因是什么?谢谢你。
编辑:
由于 HashTable 的键是 TT.X 的形式,其中 X 是一个数字,我对其进行了排序以做出正确的顺序。下面是下一个实现:
this.taskTypeList = new ArrayList<String>(0);
Map<String, String> reverseTaskMap = new HashMap<String, String>(0);
Properties properties = loadTaskProperty();
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String value = properties.getProperty(key);
reverseTaskMap.put(key, value);
}
LinkedList<Map.Entry<String, String>> linkedList = new LinkedList<Map.Entry<String, String>>(reverseTaskMap.entrySet());
Collections.sort(linkedList, new Comparator<Map.Entry<String, String>>() {
public int compare(Entry<String, String> object1, Entry<String, String> object2) {
return Integer.valueOf(Integer.parseInt(object1.getKey().split("\\.")[1])).compareTo(Integer.valueOf(Integer.parseInt(object2.getKey().split("\\.")[1])));
}
});
for (Iterator<Map.Entry<String, String>> iterator = linkedList.iterator(); iterator.hasNext(); ) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
taskTypeList.add(entry.getValue());
}
最佳答案
纯属巧合。 Properties
不保证元素的任何特定顺序,因此顺序可以是任意的。
更具体地说,以下实现细节会导致此行为:
由于您的 key 仅在最后一个字母不同,因此它们的哈希码(由
String.hashCode()
生成)仅在最后几位不同。Properties
是Hashtable
的子类。与HashMap
不同,HashTable
不应用补充哈希函数来混合哈希码位。由于Hashtable
使用 hashcode 的最后一位作为散列桶的数量来放置元素,因此您的元素将被放入后续的桶中。 这是一个非常有趣的观点 - 这意味着Hashtable
的这种实现可以在某些真实场景中显示最坏情况下的性能,而对于HashMap
这不太可能。 另一个支持HashMap
而不是Hashtable
的原因。由于某些原因,
Hashtable
的Enumeration
以相反的顺序遍历桶,因此添加的元素以相反的顺序返回。
关于java - Properties.propertyNames() 以相反的顺序返回 Enumeration - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5564734/