Java泛型,类型擦除和有界类型参数

时间:2015-10-11 01:49:32

标签: java generics

我正在尝试创建一个通用节点类,它将接受任何类型的对象作为其数据。我将类定义为

protected class Node<E> {
    E data;
    Node next;
    Node prev;

public Node(E element)
    {
      data = element;
      next = null;
      prev = null;
    }
    ...
}

public E getElement()
{
  return this.data; 
} 

稍后,我从通用getElement类调用MyLinkedList<E>方法,但得到编译错误

  Error: incompatible types
  required: E
  found:    java.lang.Object

public class DoublyLinkedList12<E> extends AbstractList<E> {

   private int nelems;
   private Node head;
   private Node tail;

   public DoublyLinkedList12()
   {
      head = new Node(null);
      tail = new Node(null);
      head.next = tail;
      tail.prev = head;
      nelems = 0;

   }
@Override
  public E next() throws NoSuchElementException
  {
    if(this.hasNext() == false){
      throw new NoSuchElementException();
    }
    left = right;
    right = right.getNext();
    forward = true;
    canRemove = true;
    idx++;
    return left.getElement(); // <== Error here
 }

我认为这是由泛型类型擦除引起的,我相信我需要使用有界参数来避免这种情况。我可以扩展哪个类以允许所有类型作为数据/是否有更有效的方法来解决这个问题?谢谢,

1 个答案:

答案 0 :(得分:0)

我猜您收到错误是因为您在MyLinkedList<E>中执行了类似的操作:

E nextElement = node.getNext().getElement();

这不起作用,因为您对Nodenext使用了raw type prev

改为使用Node<E>

为防止以后出现这种情况,请启用javac编译器警告,该警告会多次为您提供这些消息:

[rawtypes] found raw type: Node
  missing type arguments for generic class Node<E>
  where E is a type-variable:
    E extends Object declared in class Node

[unchecked] unchecked call to Node(E) as a member of the raw type Node
  where E is a type-variable:
    E extends Object declared in class Node