未经检查的调用compareTo

Dav*_*vis 0 java generics collections comparable comparator

背景

创建一个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() );
          }
      });
  ...
Run Code Online (Sandbox Code Playgroud)

Comparable作为通用参数传递给Map.Entry<K, V>(V必须是Comparable?)的语法- 以便(Comparable)警告中显示的类型转换可以被删除 - 包括我.

警告

编译器的cantankerous抱怨:

SortableValueMap.java:24:警告:[unchecked] unchecked调用compareTo(T)作为原始类型java.lang.Comparable的成员

   return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );
Run Code Online (Sandbox Code Playgroud)

如何在没有任何警告的情况下将代码更改为编译(在编译时不会抑制它们-Xlint:unchecked)?

有关

谢谢!

mha*_*ler 6

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

public class SortableValueMap<K, V extends Comparable<V>>
             extends LinkedHashMap<K, V> {
Run Code Online (Sandbox Code Playgroud)

....

    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());
        }
    });
Run Code Online (Sandbox Code Playgroud)