I have the following interface
public interface Identifiable {
public Comparable<?> getIdentifier();
}
And an implementing class
public class Agreement implements Identifiable {
private Long id;
public Comparable<Long> getIdentifier() {
return id;
}
}
EDIT: Note that there may be other implementations with different types of identifiers.
Now I would like to, yes, compare the comparables:
// Agreement a;
// Agreement b;
...
if (a.getIdentifier().compareTo(b.getIdentifier()) {
...
But the compareTo gives me the following compiler error:
The method compareTo(Long) in the type Comparable<Long> is not applicable for the arguments (Comparable<Long>)
How is this interface supposed to be used with Generics?
Comparable<T>is meant to be used as an upper bound for a generic parameter:This forces the return type to be a
T, not just something that can be compared to aT.Your code is inherently unsafe.
To understand why, consider the following code: