在我的項目中,我使用了一些屬性文件。我注意到了Properties.propertyNames()的奇怪行爲,它返回一個Enumeration,Enumeration的順序相反。我做了一個試驗: 文件內容是:Properties.propertyNames()以相反的順序返回Enumeration - 爲什麼?
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());
}
謝謝你的精彩解釋。我非常感謝你的幫助。 – 2011-04-06 10:54:04