Java: Issue combining Generics, Inner class, and “implements”

时光毁灭记忆、已成空白 提交于 2019-12-06 00:02:21

As per your definitions:

  1. HeapNode is a subtype of Node<E> but implements Comparable<Node<E>>
  2. LinkedList requires a type argument such that T implements Comparable<T>
  3. i.e. a LinkedList<HeapNode> requires that HeapNode implements Comparable<HeapNode>
  4. which it does not (from (1), above, it implements Comparable<Node<E>>)

So the two are not compatible.

You need, in LinkedList, to express the node type as a type parameter, bounded appropriately, and the node type's component type parameter as well, also bounded appropriately:

public class LinkedList<N extends Node<E>, 
                        E extends Comparable<E>> 
  implements Comparable<LinkedList<N, E>>{
  private N head;
  private N tail;
  private int size;
  ...

Now your LinkedBinaryHeap needs to adjust it's use of LinkedList:

public class LinkedBinaryHeap<E extends Comparable<E>> {
  private LinkedList<HeapNode, E> heap;

  public LinkedBinaryHeap(){
      heap = new LinkedList<HeapNode, E>();
  }

That should now compile. Whether it achieves your goals of comparing everything to everything else is harder to say!

LinkedList requires that T implements Comparable. HeapNode implements Comparable<Node<E>>. HeapNode != Node so it doesn't satisfy the type bound. Change LinkedList's declaration to T extends Comparable<? super T>. This is fine, type-wise: HeapNode is declaring that it can compare itself with any Node or subtype of Node. Of course, this means that HeapNode needs to override compareTo, but you're kind of stuck there, what with Node already implementing Comparable.

Edit: as comments point out, this answer is wrong, and not worth fixing because there's a right answer. Let it stay for posterity as a lesson in...something. How I'm not as knowledgeable on generics as I'd like to be, maybe.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!