首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

问一下,为什么下面代码关于TreeMap,Comparator会有异常

2012-01-15 
问一下,为什么下面代码关于TreeMap,Comparator会有错误问一下,为什么下面代码会有错误。谢谢。-------------

问一下,为什么下面代码关于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());              }            });    }} 

热点排行
Bad Request.