I am creating an interface and an implementation of linked list like so in Java 1.8:
public interface MyList<E extends Comparable<E>> {
.....
}
public class MyListImpl<E> implements MyList<E extends Comparable<E>>{
......
}
The interface has no compiler issues but the MyListImpl
is giving an error Unexpected Bound
where I have E extends Comparable<E>>
. I am not sure why this error is happening though.
CodePudding user response:
The bounds always go on the declaration of the generic type. That's the one at the end of the class name. The one in the implements clause is using the already declared type. So: public class MyListImpl<E extends Comparable<E>> implements MyList<E>
.
If you want to make it a bit better, use <E extends Comparable<? super E>>
. That looks the same but isn't; with just Comparable<E>
you won't be able to support classes like java.sql.Timestamp
, which extends java.util.Date
which implements Comparable<Date>
. In other words: Timestamp
is not Comparable<Timestamp>
but Comparable<Date>
, and using Comparable<? super E>
will allow you to use it.