HashMap 是一种以空间换时问的映射表,它的实现原理決定了内部的 Key 是无序的,即遍历 HashMap的 Key 时,其顺序是不可预测的(但每个Key都会遍历一次且仅遍历一次)。还有一种 Map,它在内部会对 Key 进行排序,这种 Map 就是 SortedMap。SortedMap 是接口,它的实现类是 TreeMap。
SortedMap保证遍历时以 Key 的顺序来进行排序。例如,放入的Key 是"apple""pear ""
orange",遍历的顺序一定是"apple "、" orange
"、"pear",因为 String 默认按字母排序:
1 • public class Main {
public static void main(Strin
gIl args) {
Map<String, Integer> map= new TreeMap<> ();
map. put ("orange", 1); map.put ("apple", 2); map. put ("pear", 3);
for (String key : map.key
Set()) {
System.out.println(ke
y);
/ apple, orange, pear
}
}
使用 TreeMap 时,放入的 Key 必须实现 Comparable接口。String、Integer 这些类已经
实现了 Comparable接口,因此可以直接作为 Key 使用。作为 Value 的对象则没有任何要求。