我已经创建了一个Iterator包装器,它返回元素,直到达到一定的阈值,如下所示:
public class MyIterators {
public static <E extends Comparable<E>> Iterator<E> threshold(final Iterator<? extends E> iterator, final E threshold) {
...
}
}我想将它用于实用程序函数中的Iterator<ChronoZonedDateTime>,如下所示:
public static Iterator<ZonedDateTime> oneYear(final Iterator<ZonedDateTime> iterator) {
return MyIterators.threshold(iterator, ZonedDateTime.now().plusYears(1));
}我得到了:
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<?>>)编译器推断的是ChronoZonedDateTime而不是ZonedDateTime,而我根本没有声明/使用该类。
我该怎么处理呢?我是介绍手动强制转换,还是仍然有办法以一种类型安全的方式完成所有这些?
我正在使用JDK8.x。
发布于 2019-05-17 15:17:32
我相信这个问题是由原始类型ChronoZonedDateTime引起的。如果为泛型类型ChronoZonedDateTime<?>指定通配符,则代码编译并运行:
final Iterator<ChronoZonedDateTime<?>> iterator = null;
MyIterators.threshold(iterator, ZonedDateTime.now().plusYears(1));请参阅:What is a raw type and why shouldn't we use it?
在OP编辑这个答案时,删除了问题中的一些信息。
关于第二个问题,您应该在<E extends Comparable<E>>的签名中将threshold更改为<E extends Comparable<? super E>>,这将允许您传递泛型类型与其父类型相比较的Iterator对象。
新的方法签名应该如下所示:
public static <E extends Comparable<? super E>> Iterator<E> threshold(final Iterator<? extends E> iterator, final E threshold) {https://stackoverflow.com/questions/56189111
复制相似问题