Question

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!

Was it helpful?

Solution

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.)

OTHER TIPS

You mean like

public class GenList<T extends Comparable<T>>{
//Class body.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top