Java unchecked cast

I have a comparator class in Java to compare entries in a 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;        
     }

}

when I compile this program, I get the following:

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;

I need to sort map entries based on double values.

If I create the following comparator, I get an error in calling the array sort function (I get a set of records from the map, and then use the set as an array).

public class ScoreComp implements Comparator<Map.Entry<Integer, Double>>

how to implement this scenario.

+5
source share
3 answers

, , . , : , , generics ( ). List Collections.sort():

    List<Map.Entry<Integer, Double>> mList = 
        new ArrayList<Map.Entry<Integer, Double>>(Score.entrySet()); 
    Collections.sort(mList, new ScoreComp());
+2

, TreeMap, . TreeMap , - > . , , .

final Map<Integer, Double> map = ....

public class ScoreComp implements Comparator<Integer>  {
   public int compare(Integer key1, Integer key2) {
    Double x = map.getValue();
    Double y = map.getValue();
    if (x < y)
        return -1;
    else if (x == y)
        return 0;
    else
        return 1; 
   }
}

edit: , , - , , .

public class Item implements Comparable<Item> {
   int id;
   double value;

   public int compareTo(Item other) {
      return this.value - other.value;
   }
}

List<Item> list = new ArrayList<Item>();
// ... add items here
Collections.sort(list);

Item Comparable, Comparator ( ).

+4

How about rewriting how

public class ScoreComp implements Comparator<Map.Entry<Integer, Double>> {

    public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) {
        if ( o1.getValue()  < o2.getValue()  ) return -1;
        else if ( o1.getValue() == o2.getValue()  ) return 0;
        return 1;
    }
}
+2
source

All Articles