2

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.

sshekhar
  • 137
  • 10
  • Relevant question: https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super – Shark May 27 '22 at 15:17
  • Also, `MyList newList = new MyListImpl`. And same for this: `public class MyListImpl implements MyList`. You get the `extends Comparable` from the definition of `MyList` so there's no need to rewrite that part in the definition of `MyListImpl`... unless it's complaining and i'm wrong of course :D or what Rob Spoor said, `MyListImpl> implements MyList` – Shark May 27 '22 at 15:25

1 Answers1

4

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.

Dan
  • 3,647
  • 5
  • 20
  • 26
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20