Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using bound on a parameterized type

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading