Search code examples
javagenericsinterfacecomparable

Implementing Comparable interface for a generic class with Type parameter


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?


Solution

  • Another option is, instead of implementing Comparable, have a static method that returns a Comparator, and this method can only be called when the constraint on T is met. So then your ClassX can be used with T that do not implement Comparable, but you can only obtain Comparators for ClassXs with T that do implement Comparable.

    public class ClassX<T> {
        private T o;
    
        // ...
    
        public static <T extends Comparable<? super T>> Comparator<ClassX<T>> getComparator() {
            return (x, y) -> x.o.compareTo(y.o);
        }
    }