JavaNewbie_M107
JavaNewbie_M107

Reputation: 2037

Is there a way to bound a generic type using an interface in Java?

I am trying to create a generic list which sorts the items entered into it using the .compareTo() method of the type. However, I ran into a problem in the very first line. Since the type must be one which implements Comparable<T>, is there any way to enforce this? I suppose the syntax :

public class GenList<T implements Comparable<T>>{
//Class body.
}

won't work. Any suggestions? Thanks in advance!

Upvotes: 2

Views: 627

Answers (2)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78619

You mean like

public class GenList<T extends Comparable<T>>{
//Class body.
}

Upvotes: 0

ruakh
ruakh

Reputation: 183466

I know it's a bit counter-intuitive, but for this you write extends rather than implements:

public class GenList<T extends Comparable<T>>{
//Class body.
}

(Note that I also changed the ? to T, which I think is what you meant. A reference can have type GenList<?>, or type GenList<? extends Comparable<String>>, or whatnot, but it doesn't make sense to declare the class itself as taking a wildcard parameter.)

Upvotes: 3

Related Questions