我是 Java 新手,正在使用本网站上的 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
}
}