我创建了一个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需要扩展Comparable,但我感到困惑,因为对于IteratorComparator<E extends Comparable<E>>,似乎compare方法应该是compare(E e1, E e2)
为什么用新的IteratorComparator<E>()创建IteratorComparator实例?如果将其修改为Type mismatch: cannot convert from PriorityQueue<PeekingSortedIterator<PeekingSortedIterator<E>>> to PriorityQueue<PeekingSortedIterator<E>>,为什么会出现编译时错误(new IteratorComparator<PeekingSortedIterator<E>>())?


提前致谢!

最佳答案

您必须了解E中的IteratorComparator<E extends Comparable<E>>不是具体类型,而是类型变量。

线

class IteratorComparator<E extends Comparable<E>>
    implements Comparator<PeekingSortedIterator<E>>{


为某个类型为IteratorComparatorE声明一个类Comparable<E>(与自身类似,例如StringInteger)。此类实现Comparator<PeekingSortedIterator<E>>,这意味着它可以比较两个PeekingSortedIterator<E>

09-05 09:30