有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java泛型类型参数混淆

我创建了一个PriorityQueue,其中包含PeekingSortederators,如下所示:

PriorityQueue<PeekingSortedIterator<E>> pq= new PriorityQueue<>(iterators.size(), new IteratorComparator<E>());
pq.offer(new PeekingSortedIterator<E>(si));

迭代器比较PeekingSorteditor下面的值。我的代码如下:

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());
    } 
 }

我的问题如下:

  1. 为什么IteratorComparator <E extends Comparable<E>>的类型参数不是<PeekingSortedIterator<E>>,因为类在PeekingSortedIterator<E>上操作,而不是直接在E上操作?我知道如果我这样做了,那么我需要一种不同的方法来指定E需要扩展Comparable,但是我很困惑,因为对于IteratorComparator<E extends Comparable<E>>,compare方法似乎应该是compare(E e1, E e2)

  2. 为什么使用新的IteratorComparator<E>()创建迭代器比较程序实例?如果我将编译时错误(Type mismatch: cannot convert from PriorityQueue<PeekingSortedIterator<PeekingSortedIterator<E>>> to PriorityQueue<PeekingSortedIterator<E>>)修改为new IteratorComparator<PeekingSortedIterator<E>>(),为什么会得到它

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    你必须明白IteratorComparator<E extends Comparable<E>>中的E不是一个具体的类型,而是一个类型变量

    排队

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

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