比较器 java
我的问题如下, 我有一个接口,要求我返回 java.util.Comparator
My question is the following,
I have an interface that requires me to return java.util.Comparator <E>
, my question is, how can i implement an abstract class that somehow returns a generic Comparator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以返回一个
Comparator
并抑制警告。请记住,泛型仅存在于编译时,反射除外。当它运行时,JVM 正在对原始类进行操作。因此,在运行时,所有
比较器
都是相同的类型。因此,如果您关闭警告并返回一个仅比较Object
实例的Comparator
,它将像在 Java 1.2 中一样工作。You can return a
Comparator<?>
and suppress the warnings.Keep in mind that generics exist only at compile-time, except for reflection. By the time it's runtime, the JVM is operating on the raw classes. So, at runtime, all
Comparators
are the same type. So if you turn off the warnings and return aComparator
that just comparesObject
instances, it will work just as it would have in Java 1.2.班级是什么类型?如果您有一种非抽象的方法:
为此:
您可以一次性执行此操作:
What type is the class? If you had this one way to do it non-abstractly:
For this:
You could do this as a one off:
我想接口要求您返回 Comparator是有充分理由的。 。您可以返回一个没有类型参数的比较器(实际上它是非泛型的),但它有可能会在某个地方中断。
你可以做什么:
实现一个泛型类(=它本身接受一个类型参数)并返回一个泛型比较器。
忽略(抑制)警告,尽管它可能适合您的情况,但从长远来看只会带来麻烦,而且可能不是最好的方法。
I guess there is a valid reason for the interface to require you to return a Comparator<E> . You could return a Comparator with no type parameter (which is then in fact non-generic), but there is a chance that it will break somewhere.
What you could do:
Implement a generic class (=which takes a type parameter itself) and returns a generic Comparator.
Ignoring (suppressing) warnings, although it could work in your situation, will only give trouble in the long run and probably isn't the best way to go.