TreeMap源码分析随笔(jdk1.8)

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值