问一下,为什么下面代码关于TreeMap,Comparator会有错误
问一下,为什么下面代码会有错误。谢谢。
-----------------------------------------------
Map<String, Integer> m5 = new TreeMap<String, Integer>(new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
-----------------------------------------------
Exception in thread "main"
java.lang.Error: Unresolved compilation problem:
The constructor TreeMap<String,Integer>(new Comparator<Map.Entry<String,Integer>>(){}) is undefined
------解决方案--------------------
super 是设定下限,比如 <? super A>, 类的层次为 S <- A <- B <- Object
这里就是A,B,Object是合适的,哪么S就不合适。
------解决方案--------------------
Java code
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class TestMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Map.Entry<String, Integer>, Integer> m5 = new TreeMap<Map.Entry<String, Integer>, Integer>(new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
}
}