0

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

I hope these two exmaples will cast some light on your problem:

class Foo<T> implements Comparable<T> {
    @Override
    public int compareTo(T o) {
        // We don't know anything about T
        return hashCode() - o.hashCode();
    }
}

class Boo<T extends Comparable<? super T>> implements Comparable<T> {
    private T instance;

    @Override
    public int compareTo(T o) {
        // We know that T implements Comparable<? super T>
        return instance.compareTo(o);
    }
}

In first case with Foo, you don't know anything about type T, so you can't do much in your compareTo() method.

However, in Boo, T is required to implement Comparable<? super T> (if you don't know what wildcards are, just think there is simply Comparable<T>), so you can call t.compareTo(anotherT). More about bounded type parameters.

EDIT: (wildard explained)

Consider following code:

class Car implements Comparable<Car> { ... }
class SportCar extends Car { ... }

Now call sportCar1.compareTo(SportCar2) is perfectly legal. However, without the wildcard, Bar<SportCar> is a cpompile error!

Why? Because SportCar doesn't implement Comparable<SportCar>. And you require T to implement Comparable<T>, and in this case T is SportCar.

But SportCar implements Comparable<Car> and Car is a supertype of SportCar. So you want to say something like "T can be compared to T or any supertype of T" (like in this case SportCar can be compared to any Car).

And that what the wildcard is for (among many other things). Hope this helps.

1 Comment

Ok, why am I comparing to the super type of T (whatever that is) Comparable<? super T>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.