public class ClassX<T> implements Comparable<ClassX<T>> {
private T o;
public ClassX(T o) {
this.o = o;
}
public T getObject() {
return o;
}
public void setObject(T o) {
this.o = o;
}
@Override
public int compareTo(ClassX<T> arg0) {
return o.compareTo(arg0.o);
}
}
If I have a class like this and I want to implement the Comparable interface, I read that I have to change ClassX<T> to ClassX<T extends Comparable<T>>. But what if I also want to use my ClassX for objects that don't implement the Comparable interface, knowing that I would not be able to use the method compareTo() for those objects?
Comparableinterface contract.Comparable"? That is,ClassX<T>will implementComparableif and only ifTimplementsComparable? Did I understand correctly?TtoComparable, and if it fails, throw aUnsupportedOperationException. Conditional implementation does not exist in Java.Streamof non-Comparableobjects. IfStreamuses this approach, I'd say it's fine to use it in our code too, albeit ugly.Pairclass, I suggest not doing that. Write more specific classes instead. They are more future-proof, among other things.