我想對兩個LinkedHashMap的值進行排序。我可以編譯它並運行代碼,但它告訴我在編譯期間使用-Xlint選項,因爲它是不安全的代碼。它與類型轉換的東西有關,但我對如何去做這件事感到非常困惑。我得到這個類,我在班級把inbedded:混淆瞭如何在另一個類中輸入比較器
static class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2){
int result=0;
Map.Entry e1 = (Map.Entry)obj1 ;
Map.Entry e2 = (Map.Entry)obj2 ;//Sort based on values.
Integer value1 = (Integer)e1.getValue();
Integer value2 = (Integer)e2.getValue();
if(value1.compareTo(value2)==0){
String word1=(String)e1.getKey();
String word2=(String)e2.getKey();
//Sort String in an alphabetical order
result=word1.compareToIgnoreCase(word2);
} else {
//Sort values in a descending order
result=value2.compareTo(value1);
}
return result;
}
}
我試圖調用它與我的功能之一:
ArrayList myArrayList=new ArrayList(this.map_freq_by_date.entrySet());
Collections.sort(myArrayList, new MyComparator());
Iterator itr=myArrayList.iterator();
注:this.map_freq_by_date定義如下:
Map<String,Integer> map_freq_by_date = new LinkedHashMap<String,Integer>();
我-Xlint選項得到的錯誤:
unchecked call to ArrayList(java.util.Collection<? extends E>) as a member of the raw type java.util.ArrayList
ArrayList myArrayList=new ArrayList(this.map_freq_by_date.entrySet());
unchecked conversion
found LogGrep.MyComparator
required: java.util.Comparator(? super T>
Collections.sort(myArrayList, new MyComparator());
unchecked method invocation: <T>sort(java.util.List<T>,java.util.Comparator<? super T> in java.util.Collections is applied to (java.util.ArrayList,LogGrep.MyComparator)
Collections.sort(myArrayList, new MyComparator());
幫助如何解決這些將不勝感激。我在網上查看並嘗試了各種所顯示的內容,但我似乎無法正確理解。
注:如果我把ArrayList<Object> myArrayList = new ArrayList<Object>
...錯誤更改:
unchecked method invocation <T>sort(java.util.List<T>,java.util.Comparator<> super T?) in java.util.Collections is applied ot (java.util.ArraList<java.lang.Object>,LogGrep.MyComparator)
Collections.sort(myArrayList, new MyComparator());
它沒有列出我map_freq_by_date的定義,我打算在這個問題上面。它被定義爲一個LinkedHashMap。 –
archcutbank