TreeMap

作者: ae12 | 来源:发表于2018-09-14 14:36 被阅读5次

    A Red-Black Tree based NevigableMap implementation. the map is sorted according to the natural ordering of the key or by a Comparator provided at map creation time, depending on which constructor is used.
    This implementation provides guaranteed **log(n) time cost **for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.

    hashMap 不保证数据有序,而LInkedHashMap保证数据可以保持插入顺序
    而如果希望 map 按照Key大小保持顺序,可以用TreeMap

    如果我们希望Map可以保持key的大小顺序的时候,我们就需要利用TreeMap了。

    TreeMap<Integer, String> tmap = new TreeMap<Integer, String>();
    tmap.put(1, "语文");
    tmap.put(3, "英语");
    tmap.put(2, "数学");
    tmap.put(4, "政治");
    tmap.put(5, "历史");
    tmap.put(6, "地理");
    tmap.put(7, "生物");
    tmap.put(8, "化学");
    for(Entry<Integer, String> entry : tmap.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
    

    结构图


    treeMap.png

    相关文章

      网友评论

          本文标题:TreeMap

          本文链接:https://www.haomeiwen.com/subject/ntxwgftx.html