爲了演示HashMap和TreeMap的區別,我創建了一個小代碼示例。爲什麼HashMap自動排序字符類型的鍵,雖然是一個無序的集合?
public class HashMapSimpleValueAutosort {
private static final char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap<>();
inverseAbc(map, "HashMap");
map = new TreeMap<>();
inverseAbc(map, "TreeMap");
}
private static void inverseAbc(Map<Character, Integer> map, String desc) {
System.out.println(desc);
for (int i=25; i>=0; --i) {
map.put(alphabet[i], 26 - i);
}
System.out.println(map);
}
}
它能做什麼,是分配在地圖中使用的按鍵及其在字母表中的相應值的位置內按照相反的順序字母,使用HashMap和一個TreeMap方法。
儘管按照反轉順序插入鍵,但HashMap toString()按升序輸出它們,就像TreeMap一樣。
這樣就出現在這裏的問題是:
是否toString()方法的HashMap的方法,返回地圖的字符串表示形式之前,內部排序鍵?
編輯:
它接縫,這可能是一個JDK或基於IDE症狀,而不是僅限於的toString()。
public class HashMapSimpleValueAutosort {
private static final char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
public static void main(String[] args) {
Map<Character, Integer> map = new HashMap<>();
printEntries(map, "HashMap");
map = new TreeMap<>();
printEntries(map, "TreeMap");
}
private static void printEntries(Map<Character, Integer> map, String desc) {
System.out.println(desc);
for (int i=25; i>=0; --i) {
map.put(alphabet[i], 26 - i);
}
System.out.print("{ ");
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.printf("%c=%d,", entry.getKey(), entry.getValue());
}
System.out.println(" }");
}
}
在上面的示例中,我將鍵值對作爲條目打印出來。
使用來源,盧克! – Durandal
[源代碼](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractMap.java#AbstractMap.toString%28%29 )不顯示該行爲。 –
toString()方法對此進行排序是非常不可能的。很有可能這些鍵在插入時排序(插入排序),並且toString()方法只是按照它們存儲在 – pwilmot