The difference in java generics

please i want to know the difference between spelling

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

and

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

and how will this affect the code

+6
source share
2 answers

The difference is that in the first case, a parameter of type T must be comparable with itself, while in the second case T can be comparable with anything. Typically, when the class C is comparable, it is declared that it implements Comparable<C> in any case. However, here is an example of when the first will not work, but the second will be:

 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 even the best option for the second approach would be

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

Using this parameter with C1 would also compile the string new C1<B>() .

+4
source

That's the difference.

If you are not using generics in an interface that you must execute. 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 use the generic option, you get more type safety. Casting is not required.

 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; } } 
0
source

Source: https://habr.com/ru/post/954350/


All Articles