Exorcismus
Exorcismus

Reputation: 2482

Difference in java generics

please , I want to know the difference between writing

public class Something<T extends Comparable<T>> {// }

and

public class Something<T extends Comparable> {// }

and how would that affect the code

Upvotes: 7

Views: 155

Answers (2)

arshajii
arshajii

Reputation: 129572

The difference is that in the first case the type parameter T must be comparable to itself whereas in the second case T can be comparable to anything. Generally, when a class C is made comparable it is declared to implement Comparable<C> anyway. Nevertheless, here's an example of when the first wouldn't work but the second would:

class C1<T extends Comparable<T>> {  // first case
}

class C2<T extends Comparable> {  // second case
}

class A {  // some super class
}

class B extends A implements Comparable<A> {  // comparable to super class
    @Override
    public int compareTo(A o) {
        return 0;
    }
}

Now:

new C1<B>();  // error
new C2<B>();  // works

In general, you should never use the second approach; try to stay away from raw types whenever possible. Also note that an even better option for the second approach would be

public class Something<T extends Comparable<? super T>> { /*...*/ }

Using this with C1 would allow the new C1<B>() line above to compile as well.

Upvotes: 4

duffymo
duffymo

Reputation: 309008

Here's what the difference is.

If you don't use generics in the interface you have to cast. The signature includes Object:

package generics;

/**
 * NonGenericComparable description here
 * @author Michael
 * @link http://stackoverflow.com/questions/18944582/difference-in-java-generics?noredirect=1#comment27975341_18944582
 * @since 9/22/13 10:55 AM
 */
public class NonGenericComparable implements Comparable {
    private final int x;

    public NonGenericComparable(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    @Override
    public int compareTo(Object o) {
        NonGenericComparable other = (NonGenericComparable) o;
        if (this.x < other.x) return -1;
        else if (this.x > other.x) return +1;
        else return 0;
    }
}

If you do you use the generic, you get greater type safety. Casting isn't necessary.

package generics;

/**
 * GenericComparable uses generics for Comparable
 * @author Michael
 * @link http://stackoverflow.com/questions/18944582/difference-in-java-generics?noredirect=1#comment27975341_18944582
 * @since 9/22/13 10:53 AM
 */
public class GenericComparable implements Comparable<GenericComparable> {
    private final int x;

    public GenericComparable(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    @Override
    public int compareTo(GenericComparable other) {
        if (this.x < other.x) return -1;
        else if (this.x > other.x) return +1;
        else return 0;
    }
}

Upvotes: 0

Related Questions