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.源码分析