TreeMap object的get方法返回null值

import java.util.*; public class Sort { static class ValueComparator implements Comparator { Map base; ValueComparator(Map base) { this.base = base; } @Override public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return 1; } else { return -1; } } } public static void main(String[] args) { HashMap map = new HashMap(); ValueComparator vc = new ValueComparator(map); TreeMap sorted = new TreeMap(vc); map.put("A", 1); map.put("B", 2); sorted.putAll(map); for (String key : sorted.keySet()) { System.out.println(key + " : " + sorted.get(key)); // why null values here? } System.out.println(sorted.values()); // But we do have non-null values here! } } 

输出:

 A : null B : null [1, 2] BUILD SUCCESSFUL (total time: 0 seconds) 

我想知道为什么我们在第一个注释行获取空值而我们确实有非空值,如第二个注释行所示。

编辑 :@ null的版本似乎无法正常工作。 我改变了我的代码如下:

  public int compare(String a, String b) { if (a.equals(b)) return 0; if (base.get(a) >= base.get(b)) { return 1; } else return -1; } 

它似乎工作,但我不确定。

我的猜测是你的ValueComparator.compare()方法永远不会返回0,表示相等,导致Map.get()方法找不到匹配项。

以这种方式改变您的比较

 public int compare(String a, String b) { if (base.get(a) > base.get(b)) { return 1; }else if(base.get(a) == base.get(b)){ return 0; } return -1; } 

即使你的比较器肯定坏了,如果你改变它,程序也会工作

 for (Map.Entry e : sorted.entrySet()) { System.out.println(e.getKey() + " : " + e.getValue()); }