0

背景

创建一个Map可以按值排序的。

问题

代码按预期执行,但编译不干净:

http://pastebin.com/bWhbHQmT

public class SortableValueMap<K, V> extends LinkedHashMap<K, V> {
  ...
  public void sortByValue() {
      ...
      Collections.sort( list, new Comparator<Map.Entry>() {
          public int compare( Map.Entry entry1, Map.Entry entry2 ) {
            return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );
          }
      });
  ...

Comparable将作为通用参数传递给Map.Entry<K, V>(where Vmust be ?)的语法Comparable——以便(Comparable)可以删除警告中显示的类型转换——让我无法理解。

警告

编译器的脾气暴躁的抱怨:

SortableValueMap.java:24: 警告: [unchecked] unchecked call to compareTo(T) as a member of raw type java.lang.Comparable

   return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );

问题

如何更改代码以在没有任何警告的情况下进行编译(在使用 编译时不抑制它们-Xlint:unchecked)?

有关的

谢谢!

4

3 回答 3

6

声明V扩展Comparable<V>接口的类型。这样,您可以删除Map.Entry对象的强制转换(Comparable)并改为使用推断的类型:

public class SortableValueMap<K, V extends Comparable<V>>
             extends LinkedHashMap<K, V> {

……

    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> entry1, Map.Entry<K, V> entry2) {
            return entry1.getValue().compareTo(entry2.getValue());
        }
    });
于 2011-01-02T05:43:37.740 回答
2

该值应该是可比较的子类。

SortableValueMap<K, V extends Comparable>

试试上面的。

于 2011-01-02T05:51:15.773 回答
1

将 Comparable 作为通用参数传递给 Map.Entry 的语法(其中 V 必须是 Comparable?)——以便可以删除警告中显示的 (Comparable) 类型转换——让我无法理解。

怎么样:

public class SortableValueMap <K, V extends Comparable<V>> extends LinkedHashMap<K, V> { 
  ...
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> entry1, Map.Entry<K, V> entry2) {
            return (entry1.getValue()).compareTo(entry2.getValue());
        }
    });

但这可能会更好,具体取决于您的意图:

public class SortableValueMap <K, V extends Comparable<? super V>> extends LinkedHashMap<K, V> { ...

请参阅http://download.oracle.com/javase/tutorial/extra/generics/morefun.html

T 没有必要与它本身完全可比。所需要的只是 T 与其超类型之一相当。这给了我们:

public static <T extends Comparable<? super T>>  max(Collection<T> coll)

...这个推理适用于几乎所有旨在用于任意类型的 Comparable 用法:您总是希望使用Comparable <? super T>. ...

于 2011-01-02T05:54:44.493 回答