简体   繁体   English

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

[英]Java Generics, Type Erasure and Bounded Type Parameters

I am trying to create a generic node class that will accept any type of object as its data. 我正在尝试创建一个通用节点类,该类将接受任何类型的对象作为其数据。 I define the class as 我将类定义为

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

Later, I call the getElement method from a generic MyLinkedList<E> class, but get the compilation error 稍后,我从通用MyLinkedList<E>类调用getElement方法,但得到编译错误

  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
 }

I believe this is caused by generic type erasure, and I believe I need to use bounded parameters to avoid this. 我相信这是由通用类型擦除引起的,并且我相信我需要使用有界参数来避免这种情况。 What class can I extend as to allow all types as data/is there a more efficient way to go about this? 我可以扩展哪种类以允许所有类型作为数据/是否有更有效的方法来解决此问题? Thanks, 谢谢,

I guess you are getting the error because you are doing something like this in MyLinkedList<E> : 我猜您正在收到错误,因为您正在MyLinkedList<E>

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

This doesn't work because you are using the raw type Node for next and prev . 这不起作用,因为您将原始类型 Node用于nextprev

Use Node<E> instead. 请改用Node<E>

To prevent this in the future, enable the javac compiler warnings, which would have given you these messages multiple times: 为了将来避免这种情况,请启用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM