Java泛型类型参数混淆
我创建了一个PriorityQueue,其中包含PeekingSortederators,如下所示:Java泛型类型参数混淆,java,generics,Java,Generics,我创建了一个PriorityQueue,其中包含PeekingSortederators,如下所示: PriorityQueue<PeekingSortedIterator<E>> pq= new PriorityQueue<>(iterators.size(), new IteratorComparator<E>()); pq.offer(new PeekingSortedIterator<E>(si)); class Iterat
PriorityQueue<PeekingSortedIterator<E>> pq= new PriorityQueue<>(iterators.size(), new IteratorComparator<E>());
pq.offer(new PeekingSortedIterator<E>(si));
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());
}
}
PriorityQueue pq=newpriorityqueue(iterators.size(),new iterator comparator());
pq.报价(新PeekingSorteditor(si));
迭代器比较PeekingSorteditor下面的值。我的代码如下:
PriorityQueue<PeekingSortedIterator<E>> pq= new PriorityQueue<>(iterators.size(), new IteratorComparator<E>());
pq.offer(new PeekingSortedIterator<E>(si));
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());
}
}
类迭代器Comparator实现比较器{//注意泛型!!!
@凌驾
公共整数比较(PeekingSorteditor o1,PeekingSorteditor o2){
返回o1.peek().compareTo(o2.peek());
}
}
我的问题如下:
PriorityQueue<PeekingSortedIterator<E>> pq= new PriorityQueue<>(iterators.size(), new IteratorComparator<E>());
pq.offer(new PeekingSortedIterator<E>(si));
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());
}
}
迭代器comparator
的类型参数是而不是
,因为类在PeekingSorteditor
上操作,而不是直接在E上操作?我知道如果我这样做了,那么我需要一种不同的方法来指定E需要扩展Comparable,但是我很困惑,因为对于IteratorComparator
,比较方法应该是compare(ee1,ee2)
IteratorComparator()
创建IteratorComparator实例?如果我将其修改为新迭代器Comparator()
,为什么会出现编译时错误(类型不匹配:无法从PriorityQueue转换为PriorityQueue
)提前谢谢 您必须了解
IteratorComparator
中的E
不是一个具体类型,而是一个类型变量
线路
class IteratorComparator<E extends Comparable<E>>
implements Comparator<PeekingSortedIterator<E>>{
类迭代器比较器
执行比较器{
为某种类型的
E
声明一个类迭代器Comparator
,该类型是可比的
(与自身可比,例如字符串
或整数
)。此类实现了比较器
,这意味着它可以比较两个PeekingSorteditor
s
不作为类型参数编译。请尝试构造一个这样的示例,您将看到为什么这样做。那么将其指定为类迭代器或Comparator implements Comparator会更正确吗代码>?即使这样,我也不能使用新的迭代器Comparator()
因为现在类需要2个类型参数。谢谢Thomas。我想我的困惑是,如果我需要为Comparator指定
,那么为什么不为类迭代器Comparator指定呢,因为不管怎么说,它是比较2'Peek排序器的类。还是我不需要指定迭代器Comparator
因为编译器已经知道该类将在“PeekingSorteditor”上操作,因为我们已经指定,当我们指定该类实现在PeekingSorteditor
上操作的Comparator时,WorldGoes通过编写implements Comparator
可以告诉编译器您的class将进行比较(peekingsorteditor
)。peekingsorteditor
本身有一个类型参数E
,您需要指定(peekingsorteditor
)或者必须在类中声明(iterator
)