咱们在一般写一个Map的时候,必定会用到HashMap,并且只要有相关的Map数据结构的需求,就会使用HashMap,但其实还有一个容器TreeMap,若是使用好的话会有很好的效果。java
TreeMap是什么 TreeMap是一个特殊的Map,它的全部元素都是根据key值进行排序的。数据结构
TreeMap的要求 TreeMap由于是根据key值进行排序的,因此它的一个很是重要的要求是key的类必定是继承了Comparable接口的。若是咱们运行以下的代码:code
public class Test { public static void main(String[] args) { Map<Student, Integer > map = new TreeMap<>(); map.put(new Student(), 1); System.out.println(map.size()); } @Data static class Student { String name; } }
咱们会有以下的报错:orm
Exception in thread "main" java.lang.ClassCastException: com.makun.performance.Test$Student cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1294) at java.util.TreeMap.put(TreeMap.java:538) at com.makun.performance.Test.main(Test.java:16)