[英]How to cope with a class which implements Comparable<?> and not Comparable<E>?
I have created an Iterator
wrapper which returns elements until a certain threshold is reached as following: 我创建了一个Iterator
包装器,该包装器返回元素直到达到某个阈值,如下所示:
public class MyIterators {
public static <E extends Comparable<E>> Iterator<E> threshold(final Iterator<? extends E> iterator, final E threshold) {
...
}
}
I want to use this for an Iterator<ChronoZonedDateTime>
in a utility function as following: 我想将其用于实用程序函数中的Iterator<ChronoZonedDateTime>
,如下所示:
public static Iterator<ZonedDateTime> oneYear(final Iterator<ZonedDateTime> iterator) {
return MyIterators.threshold(iterator, ZonedDateTime.now().plusYears(1));
}
I am getting: 我正进入(状态:
method threshold in class MyIterators cannot be applied to given types;
[ERROR] required: java.util.Iterator<? extends E>,E
[ERROR] found: java.util.Iterator<java.time.chrono.ChronoZonedDateTime>,java.time.ZonedDateTime
[ERROR] reason: cannot infer type-variable(s) E
[ERROR] (argument mismatch; java.util.Iterator<java.time.chrono.ChronoZonedDateTime> cannot be converted to java.util.Iterator<? extends java.time.chrono.ChronoZonedDateTime<?>>)
The compiler is inferring ChronoZonedDateTime
instead of ZonedDateTime
, while I am not declaring/using that class at all. 编译器推断ChronoZonedDateTime
而不是ZonedDateTime
,而我根本没有声明/使用该类。
How do I cope with this? 我该如何处理? Do I introduce a manual cast, or is there still a way to do all this in a type-safe manner? 我要引入手动转换,还是有一种以类型安全的方式完成所有这些转换的方法?
I am working with JDK 8.x. 我正在使用JDK8.x。
I believe the issue is caused by the raw type, ChronoZonedDateTime
. 我相信问题是由原始类型ChronoZonedDateTime
引起的。 If you specify a wildcard for the generic type, ChronoZonedDateTime<?>
, then your code compiles and runs: 如果为通用类型ChronoZonedDateTime<?>
指定通配符,则代码将编译并运行:
final Iterator<ChronoZonedDateTime<?>> iterator = null;
MyIterators.threshold(iterator, ZonedDateTime.now().plusYears(1));
See: What is a raw type and why shouldn't we use it? 请参阅: 什么是原始类型,为什么我们不应该使用它?
Editing this answer as OP removed some information from the question. 在OP中编辑此答案会从问题中删除一些信息。
Regarding your second problem, you should change <E extends Comparable<E>>
to <E extends Comparable<? super E>>
关于第二个问题,您应该将<E extends Comparable<E>>
更改为<E extends Comparable<? super E>>
<E extends Comparable<? super E>>
in the signature of threshold
, which will allow you to pass in Iterator
objects whose generic type is one that compares against its parent type. threshold
签名中的<E extends Comparable<? super E>>
,它将允许您传递通用类型为与其父类型进行比较的Iterator
对象。
The new method signature should look like the following: 新方法签名应如下所示:
public static <E extends Comparable<? super E>> Iterator<E> threshold(final Iterator<? extends E> iterator, final E threshold) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.