我是Java新手,正在使用本站上的TreeMap代码示例,但是当我尝试遍历TreeMap时,我得到一个空值列表,但是当我直接打印地图时,可以看到键/值对。我该如何纠正这一点?当我从TreeMap打印出值时,为什么会得到空值列表?
import java.util.*;
public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator1 bvc = new ValueComparator1(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
map.put("A",99.5);
map.put("B",67.4);
map.put("C",67.4);
map.put("D",67.3);
System.out.println("unsorted map: "+map);
sorted_map.putAll(map);
System.out.println("results: "+sorted_map);
for(String key: sorted_map.keySet())
{
System.out.println(sorted_map.get(key)); //null values-Why?
}
}
}
class ValueComparator1 implements Comparator<String> {
Map<String, Double> base;
public ValueComparator1(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
实现那只是需要的东西?因为在这个例子中我所有的键都不同。仍然不明白这个编辑背后的原因。它工作顺便。 – lord12
这是必要的,因为当你调用get(“A”)时,并且地图查看“A”的条目时,原始比较器说明键不相等,所以它不会返回该条目。 –