开发者

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

开发者 https://www.devze.com 2022-12-29 02:21 出处:网络
I wanted to do something along the lines of: public class MyClass<T implements Comparable> { ....

I wanted to do something along the lines of:

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

But I can't, since,开发者_运维知识库 apparently, generics only accept restrictions with subclasses, and not interfaces.

It's important that I'm able to compare the types inside the class, so how should I go about doing this? Ideally I'd be able to keep the type safety of Generics and not have to convert the T's to Object as well, or just not write a lot of code overall. In other words, the simplest the better.


The implements is wrong. It only accepts extends or super. You can use here extends:

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

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


The best way to do it is:

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

If you just do <T extends Comparable<T>>, then it won't work for subclasses of comparable classes.


Also for interfaces you have to use extends. So in your case it would be:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号