当我们使用TreeMap 去按添加顺序取出的时候,并且我们不希望去重,我们通过比较器排序完成需求后,然后我们这个时候我们就想用ketSet 通过遍历 去得到他的value,然后我们就发现拿不到值。
public class Exer_6 {
public static void main(String[] args) {
TreeMap map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return 1;
}
});
map.put(111, 222);
map.put(333, 222);
map.put(111, 222);
map.put(444, 222);
map.put(222, 222);
Set keySet = map.keySet();
for(Object obj : keySet) {
System.out.println(obj+"::"+map.get(obj));
}
}
}
执行结果:
经过一番了解,才知道TreeMap 存取数据都是通过比较器去比较的 存的时候就是 普通排序的规则,但是取的时候 是key去调get方法 这个时候就会调用比较器去比较 比较的结果必须返回 0 才能被取出,否则是找不到值的。上述我们在比较器中return 的一直都是 1 所以才会存在找不到值的情况。
所以当我们遇到了这种情况我们可以通过entrySet去遍历,因为entrySet可行是因为一开始就把key和value的值存在Set集合中。而不是key去get 它的value的。
public static void main(String[] args) {
TreeMap<Integer, Integer> map = new TreeMap(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return 1;
}
});
map.put(111, 222);
map.put(333, 222);
map.put(111, 222);
map.put(444, 222);
map.put(222, 222);
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
for (Entry<Integer, Integer> entry : entrySet) {
System.out.println(entry.getKey() + "::" + entry.getValue());
}
}
当然如果你要当铁脑壳,一定要去用keySet,也不是没有办法,就是把他的存取过程分开,可以设置一个boolean变量,当我们存完了我们就改变这个boolean变量即可,这只是一种思路,但是我不会选择,因为我不是铁脑壳。
所以说 在我们 不去重和按添加的顺序取出 在我们使用TreeSet的情况下,就用 entrySet 遍历;