TreeMap--一个排序了的映射

咱们在一般写一个Map的时候,必定会用到HashMap,并且只要有相关的Map数据结构的需求,就会使用HashMap,但其实还有一个容器TreeMap,若是使用好的话会有很好的效果。java

  1. TreeMap是什么 TreeMap是一个特殊的Map,它的全部元素都是根据key值进行排序的。数据结构

  2. 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)
  1. TreeMap的内部结构是什么样的 TreeMap的实现从根本上讲是红黑树,红黑树做为一种优秀的数据结构,被普遍应用到了jdk的源码编写当中,至于红黑树的结构、性质与转换规则,咱们会在之后的博客里介绍
相关文章
相关标签/搜索