Search code examples
javacomparable

Java Comparable for Generic Types


When trying to compare a generic type in the form

  Class<T> implements Comparable<T> {

      public int compareTo(T other){
        this.T < other
      } 
  }

does not work for me but when using

  Class<T extends Comparable<T>>{
     T.compareTo(other.T)
  }

does work. I have been unable to deciper why I can't compare T directly using the first example


Solution

  • In your first example:

    class Foo<T> implements Comparable<T> {
    

    you're saying that Foo objects are comparable. In your second example:

    class Foo<T extends Comparable<T>>{
    

    you're saying that whatever T, is, it's comparable.

    Then, in the body of your code, you try to compare things of type T -- in the first case, you have no guarantee that they're comparable, in the second, you do.