通用类型扩展接口,无法访问接口方法而无需警告

lsu*_*und 1 java generics hashmap comparable

如果我有一个泛型类,

public class Graph<K, V extends Comparable> {
     ...
 }
Run Code Online (Sandbox Code Playgroud)

我的理解是,任何类型的对象V都具有可比性,因为它扩展了Comparable接口.现在我想HashMap<K, V>在课堂上使用.V我的地图中的类型对象仍应具有可比性.我声明了一个方法:

public V getMin(HashMap<K, V> map, V zero) {
     V min = zero;
     for (V value : map.values()) {
         if (value.compareTo(min) < 0) {
            min = value;
         }
     }
     return min;
}
Run Code Online (Sandbox Code Playgroud)

编译时,我收到警告

warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type
Comparable

if (value.compareTo(min) < 0) {

where T is a type-variable:
T extends Object declared in interface comprable
Run Code Online (Sandbox Code Playgroud)

我将此警告解释为编译器不确定是否value具有可比性.为什么不?这是什么问题,我该如何解决它?

Lui*_*oza 7

Comparableinterface被声明为raw.它应该用作

YourGenericInterfaceHere extends Comparable<YourGenericInterfaceHere>
Run Code Online (Sandbox Code Playgroud)

要么

YourGenericClassHere implements Comparable<YourGenericClassHere>
Run Code Online (Sandbox Code Playgroud)

在泛型中,您将使用它extends:

YourGenericElement extends Comparable<YourGenericElement>
Run Code Online (Sandbox Code Playgroud)

简而言之,您应该将您的课程声明为:

public class Graph<K, V extends Comparable<V>> {
    //rest of code...
}
Run Code Online (Sandbox Code Playgroud)