[英]java unchecked cast
我在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;
}
}
當我編譯這個程序時,我得到以下內容:
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;
我需要根據Double Values對映射條目進行排序。
如果我創建了下面的比較器,那么在調用Arrays的sort函數時會出現錯誤(我從地圖中獲取一個條目集,然后使用set作為數組)。
public class ScoreComp implements Comparator<Map.Entry<Integer, Double>>
如何實現這種情況。
假設您正在使用此比較器對TreeMap
進行排序,那么這不會起作用。 TreeMap
比較器僅用於比較映射鍵,而不是key-> value條目。 如果你的比較器需要訪問這些值,那么它必須在地圖本身中查找它們,例如
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;
}
}
編輯:從您的評論中,我認為您最好的選擇是創建一個封裝ID和值的類,將這些值放入List中,然后對其進行排序。
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
(除非您需要)。
什么是重寫為
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;
}
}
stacker描述了如何修復你顯示的代碼。 以下是如何修復注釋中的代碼:首先,不要使用數組,因為數組不能使用泛型(您不能使用泛型類型的數組)。 相反,您可以使用List
和Collections.sort()
方法:
List<Map.Entry<Integer, Double>> mList =
new ArrayList<Map.Entry<Integer, Double>>(Score.entrySet());
Collections.sort(mList, new ScoreComp());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.