Type mismatch: cannot convert from element type Object to Map.Entry<String,String>

Type mismatch: cannot convert from element type Object to Map.Entry<String,String>

出现这个错误我是把出错的地方涉及到的方法,全部用到的

参数类型要写完整

,就不报错了。这个错误在有的本地开发环境不会报错,但是做成接口供外部调用接口时就可能会失败了,所以,要养成所有类型写规范的习惯。

方法块示例:

 public static List<Entry<String, Long>> sortByValueAsc(TreeMap<String, Long> map) {
    
    
        List<Entry<String, Long>> list =
                new ArrayList<Entry<String, Long>>(map.entrySet());
        
        Collections.sort(list, new Comparator<Entry<String, Long>>() {
    
    
            @Override
            public int compare(Entry<String, Long> o1,
                    Entry<String, Long> o2) {
    
    
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        return list;
    }

调用示例

 TreeMap map = new TreeMap<>();
        map.put("231", 3213L);
        map.put("41", 23231231L);
        map.put("24", 201L);
        map.put("2321", 321L);
        map.put("3213", 3L);
        for (Entry<String, Long> entry : MapSortUtil.sortByValueAsc(map).subList(2, 5)) {
    
    
            System.out.println(entry.getKey()+"------"+entry.getValue());
        }

因为map的类型没有写完整而报错,修改为:

 TreeMap<String, Long> map = new TreeMap<>();

猜你喜欢

转载自blog.csdn.net/weilikk/article/details/110366904
今日推荐