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!
}
}
Output:
A : null
B : null
[1, 2]
BUILD SUCCESSFUL (total time: 0 seconds)
I wonder why we get null values at the first commented line while we do have non-null values as demonstrated by the second commented line.
Edit: @null's version seems not working. I've changed my code as follows:
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;
}
It seems to work but I'm not sure.
My guess is that your ValueComparator.compare()
method never returns 0, indicating equality, causing the Map.get()
method to not find matches.
Change your compare to in this way
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;
}
Even with your Comparator which is definitely broken the program will work if you change it as
for (Map.Entry e : sorted.entrySet()) {
System.out.println(e.getKey() + " : " + e.getValue());
}
来源:https://stackoverflow.com/questions/13842830/treemapstring-integer-objects-get-method-return-null-value