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 to share