Java: Is it possible to have a generic class that only uses types that can be compared?

I wanted to do something like:

public class MyClass<T implements Comparable> {
    ....
}

      

But I can't, since apparently generics only allow constraints with subclasses, not interfaces.

It is important that I can compare types within a class, so how should I do this? Ideally I could keep the Generics type safety and shouldn't convert T to Object, and also just not write a lot of code in general. In other words, the simplest the better.

+2


a source to share


3 answers


Unfaithful implements

. It only accepts extends

or super

. You can use here extends

:

public class MyClass<T extends Comparable<T>> {
    // ...
}

      



To learn more about Generics, you can find this tutorial (PDF) .

+7


a source


The best way to do it:

public class MyClass<T extends Comparable<? super T>> {
    ....
}

      



If you're just doing <T extends Comparable<T>>

, then it won't work for subclasses of comparable classes.

+3


a source


Also for interfaces, you should use extends. So in your case it would be:

public class MyClass<T extends Comparable<T>> {
....
}

      

+1


a source







All Articles