1.使用方法
TreeMap與HashMap類似,存的也是鍵值對,但HashMap是無序的,TreeMap能根據Key進行排序,使用用例如下:
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap<Integer,String> tmap=new TreeMap<>();
tmap.put(3, "好");
tmap.put(6, "JAVA");
tmap.put(4, "啊");
tmap.put(1, "你");
Set<Integer> keySetStr=tmap.keySet();
Iterator<Integer> iteKey=keySetStr.iterator();
System.out.print("輸出TreeMap中的元素爲:");
while(iteKey.hasNext()) {
System.out.print(tmap.get(iteKey.next())+" ");
}
System.out.println("");
}
運行結果爲:
輸出TreeMap中的元素爲:你 好 啊 JAVA
可見,元素順序是排好序的,其中根據key值排序是因爲Key爲Integer類型,而Integer默認實現了Comparable<Integer>接口,所以默認按升序排列。因此需要注意的是,當需要根據其他類型的值進行排序時,比如我們自定義的對象,該對象也要實現Comparable接口指定排序方式,否則就會出錯,如代碼,其中KeyTest對象沒有實現Comparable接口:
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap<KeyTest,String> tmap2=new TreeMap<>();
KeyTest k1=new KeyTest();
KeyTest k2=new KeyTest();
KeyTest k3=new KeyTest();
tmap2.put(k1, "測試Key是否出錯!");
tmap2.put(k2, "測試Key是否出錯!");
tmap2.put(k3, "測試Key是否出錯!");
Set<KeyTest> keySetStr=tmap2.keySet();
Iterator<KeyTest> iteKey=keySetStr.iterator();
System.out.print("輸出TreeMap中的元素爲:");
while(iteKey.hasNext()) {
System.out.print(tmap2.get(iteKey.next())+" ");
}
}
當運行後,會出現ClassCastException:
Exception in thread "main" java.lang.ClassCastException: MapStudy.KeyTest cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at MapStudy.TMapStudy.main(TMapStudy.java:29)
2.源碼分析