Ter*_* Li 2 java hashmap key-value treemap
import java.util.*;
public class Sort {
static class ValueComparator implements Comparator<String> {
Map<String, Integer> base;
ValueComparator(Map<String, Integer> 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<String, Integer> map = new HashMap<String, Integer>();
ValueComparator vc = new ValueComparator(map);
TreeMap<String, Integer> sorted = new TreeMap<String, Integer>(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!
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
A : null
B : null
[1, 2]
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)
我想知道为什么我们在第一个注释行获取空值,而我们确实有非空值,如第二个注释行所示.
编辑:@ 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;
}
Run Code Online (Sandbox Code Playgroud)
它似乎工作,但我不确定.
| 归档时间: |
|
| 查看次数: |
5735 次 |
| 最近记录: |