我创建了一个包含PriorityQueue的PeekingSortedIterators,如下所示:
PriorityQueue<PeekingSortedIterator<E>> pq= new PriorityQueue<>(iterators.size(), new IteratorComparator<E>());
pq.offer(new PeekingSortedIterator<E>(si));
IteratorComparator比较PeekingSortedIterator的底层值。我的代码如下:
class IteratorComparator<E extends Comparable<E>> implements Comparator<PeekingSortedIterator<E>>{ // note generics!!!
@Override
public int compare(PeekingSortedIterator<E> o1, PeekingSortedIterator<E> o2) {
return o1.peek().compareTo(o2.peek());
}
}
我的问题如下:
IteratorComparator <E extends Comparable<E>>
的类型参数不是<PeekingSortedIterator<E>>
,因为类在PeekingSortedIterator<E>
上操作,而不是直接在E上操作?我知道,如果我这样做了,那么我需要一种不同的方法来指定E需要扩展可比较,但我很困惑,因为在IteratorComparator<E extends Comparable<E>>
中,比较方法应该是compare(E e1, E e2)
。IteratorComparator<E>()
实例?如果我将编译时错误(Type mismatch: cannot convert from PriorityQueue<PeekingSortedIterator<PeekingSortedIterator<E>>> to PriorityQueue<PeekingSortedIterator<E>>
)修改为new IteratorComparator<PeekingSortedIterator<E>>()
,为什么要得到它?提前感谢!
发布于 2017-11-23 22:39:29
您必须理解,E
在IteratorComparator<E extends Comparable<E>>
中不是一个具体的类型,而是一个类型变量。
线
class IteratorComparator<E extends Comparable<E>>
implements Comparator<PeekingSortedIterator<E>>{
为某种类型的IteratorComparator
( E
)声明一个类Comparable<E>
(可与其自身相比较,例如String
或Integer
)。这个类实现Comparator<PeekingSortedIterator<E>>
,这意味着它可以比较两个PeekingSortedIterator<E>
的
https://stackoverflow.com/questions/47465798
复制相似问题