我使用这种方法对我的哈希函数进行排序。当我编译程序时,出现以下错误:
Note: Retriever.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
我的hashMap<String, Double>
private static Map sortByComparator(Map unsortMap) {
List list = new LinkedList(unsortMap.entrySet());
// sort list based on comparator
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o2)).getValue())
.compareTo(((Map.Entry) (o1)).getValue());
}
});
// put sorted list into map again
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
最佳答案
这是一个编译器警告,因为您忽略了泛型并使用“原始”类型。 Ypu 需要指定泛型如下:
private static <K, V extends Comparable<V>> Map<K, V> sortByComparator(Map<K, V> unsortMap) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(unsortMap.entrySet());
//sort list based on comparator
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
//put sorted list into map again
Map<K, V> sortedMap = new LinkedHashMap<K, V>();
for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) {
Map.Entry<K, V> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
这里发生的事情是,通过指定泛型类型,您可以告诉编译器这些集合包含哪些类型的对象。因此,我已经能够消除比较器和第二个循环中的所有强制转换。这使得该方法实际上类型安全并且可由编译器检查。
编译器通过警告告诉您的是,因为您使用的是原始类型并进行强制转换,所以它无法检查输入的准确性。另一种选择是简单地使用 @SuppressWarnings 抑制此警告,但最好实际上使方法类型安全。
关于java - 排序哈希函数和编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433576/