Generic type extending interface, cant access interface methods without warning

1.1k Views Asked by At

If I have a generic class,

public class Graph<K, V extends Comparable> {
     ...
 }

My understanding is that any object of type V is going be comparable since it extends the interface Comparable. Now I want to use a HashMap<K, V> inside my class. An object of type V inside my map should still be comparable. I declare a method:

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;
}

When compiling, I get warning

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

I interpret this warning as that the compiler is not sure whether value is comparable or not. Why not? What is the problem here and how do I get around it?

2

There are 2 best solutions below

1
On BEST ANSWER

Comparable interface is declared as raw. It should be used as

YourGenericInterfaceHere extends Comparable<YourGenericInterfaceHere>

or

YourGenericClassHere implements Comparable<YourGenericClassHere>

In generics, you will use it with extends:

YourGenericElement extends Comparable<YourGenericElement>

In short, you should declare your class as:

public class Graph<K, V extends Comparable<V>> {
    //rest of code...
}
1
On

Comparable is a generic type, so when declaring that the type parameter V extends Comparator, the interface should be parameterized:

public class Graph<K, V extends Comparable<V>> {