java - 排序哈希函数和编译错误

标签 java sorting collections hashmap

我使用这种方法对我的哈希函数进行排序。当我编译程序时,出现以下错误:

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/

相关文章:

c# - 为什么这个 foreach 循环不抛出异常“集合被修改,枚举操作可能无法执行”。

java - Collections.emptyList() 是 Collections.EMPTY_LIST 的替代品吗?

java - 如何在 JFreeChart 折线图上创建形状?

java - 如何将具有特殊字符的字符串转换为转义的另一个字符串

c# - 如何对字符串进行排序,以便首先搜索以搜索词开头的字符串?

c++ - 使用成员函数对类对象数组进行排序

java - 自定义 JLabel 类打破了 JLabel 的定位

java - java中如何将整数存储到字符串多维数组中

python - 我写了一个排序算法。这是快速排序吗?

java - 在 java 映射中使用非 Ascii 字符串作为键时没有得到任何值