簡體   English   中英

Java泛型類型參數混亂

[英]Java generics type parameter confusion

我創建了一個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());
    } 
 }

我的問題如下:

  1. 為什么IteratorComparator <E extends Comparable<E>>的類型參數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>()創建IteratorComparator實例? 如果我將其修改為new IteratorComparator<PeekingSortedIterator<E>>()為什么會出現編譯時錯誤( Type mismatch: cannot convert from PriorityQueue<PeekingSortedIterator<PeekingSortedIterator<E>>> to PriorityQueue<PeekingSortedIterator<E>> new IteratorComparator<PeekingSortedIterator<E>>()

提前致謝!

你必須明白, EIteratorComparator<E extends Comparable<E>>是不是一個具體的類型,但類型變量。

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

為某個類型E聲明一個IteratorComparator類,該類型為Comparable<E>Comparable<E>本身可比較,例如StringInteger )。 此類實現Comparator<PeekingSortedIterator<E>> ,這意味着它可以比較兩個PeekingSortedIterator<E>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM