Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in java generics

Tags:

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

like image 977
Exorcismus Avatar asked Sep 22 '13 13:09

Exorcismus


People also ask

What is difference between T and in Java generics?

6 Answers. Show activity on this post. Well there's no difference between the first two - they're just using different names for the type parameter ( E or T ). The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?>

What is the difference between List <? Super T and List <? Extends T?

super is a lower bound, and extends is an upper bound.

What does <? Super E mean?

super E> , it means "something in the super direction" as opposed to something in the extends direction. Example: Object is in the super direction of Number (since it is a super class) and Integer is in the extends direction (since it extends Number ).


1 Answers

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.

like image 77
arshajii Avatar answered Sep 23 '22 22:09

arshajii