java unchecked cast

Roh*_*nga 5 java generics compiler-warnings

我在Java中有一个比较器类来比较Map条目:

public class ScoreComp implements Comparator<Object> {

    public int compare(Object o1, Object o2) {

        Entry<Integer, Double> m1 = null;
        Entry<Integer, Double> m2 = null;

        try {
            m1 = (Map.Entry<Integer, Double>)o1;
            m2 = (Map.Entry<Integer, Double>)o2;
        } catch (ClassCastException ex){
            ex.printStackTrace();
        }

        Double x = m1.getValue();
        Double y = m2.getValue();
        if (x < y)
            return -1;
        else if (x == y)
            return 0;
        else
            return 1;        
     }

}
Run Code Online (Sandbox Code Playgroud)

当我编译这个程序时,我得到以下内容:

warning: [unchecked] unchecked cast
found   : java.lang.Object
required: java.util.Map.Entry<java.lang.Integer,java.lang.Double>
            m1 = (Map.Entry<Integer, Double>)o1;
Run Code Online (Sandbox Code Playgroud)

我需要根据Double Values对映射条目进行排序.

如果我创建了下面的比较器,那么在调用Arrays的sort函数时会出现错误(我从地图中获取一个条目集,然后使用set作为数组).

public class ScoreComp implements Comparator<Map.Entry<Integer, Double>>
Run Code Online (Sandbox Code Playgroud)

如何实现这种情况.

Mic*_*rdt 2

stacker 已经描述了如何修复您所显示的代码。以下是如何修复注释中的代码:首先,不要使用数组,因为数组不能与泛型一起使用(您不能拥有泛型类型的数组)。相反,您可以使用 aList和Collections.sort()方法:

    List<Map.Entry<Integer, Double>> mList = 
        new ArrayList<Map.Entry<Integer, Double>>(Score.entrySet()); 
    Collections.sort(mList, new ScoreComp());
Run Code Online (Sandbox Code Playgroud)