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());
}
结构图

网友评论