Java Generics and Comparables

      No Comments on Java Generics and Comparables

When designing a generic class which needs a parameter that is comparable you will probably end up with something like this:

public interface Page<K extends Comparable<K>>
public class LocalPage<K extends Comparable<K>> implements Page<K>

Unfortunately, using Comparable isn’t as “easy”. The Page interface described above can’t be instantiated for a type like java.sql.Time, which is not Comparable to itself, but to a supertype (i.e., java.sql.Time implements Comparable<java.util.Date>).
David Hall suggests: “If you’re going to declare types that implement Comparable, you probably need to be in the habit of writing the declaration as:”

public interface Page<K extends Comparable<? super K>>
public class LocalPage<K extends Comparable<? super K>> implements Page<K>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.