Java中的单链表 - get()方法

gma*_*man 2 java generics

我是Java的新手,并尝试在Java中实现单链表.我已经包含了泛型的使用.代码如下所示:

public class LinkedListX<E>{

   Node <E> head;
   int size;

   LinkedListX(){
       head = null;
       size = 0;
   }

   LinkedListX (E e){
       head = new Node(e);
       size = 1;
   }

   void add(E e){
       if (head == null){
           head = new Node (e);
       } else {
           Node current = this.head;
           while (current.next != null){
               current = current.next;
           }
           current.next = new Node(e);
       }
       size++;
   }

   E get (int n){
       if (n > size){
           return null;
       }
       Node current = head;
       for (int i=1;i<n;i++){
           current = current.next;
       }
       return current.e;
   }

   private class Node<E> {
       private E e;
       private Node next;

       Node (E e, Node n){
           this.e = e;
           this.next = n;
       }
       Node (E e) {
           this.e = e;
       }
   }
Run Code Online (Sandbox Code Playgroud)

}

get()方法给出错误消息

不兼容的类型,要求:E,Found:java.lang.Object"at"return current.e

我想我是以错误的方式使用泛型.有人能让我知道编码这种方法的正确方法吗?

谢谢.

Lin*_*ica 5

作为Node内部类,它还可以访问外部类泛型参数.并且您永远不会分配E与外部类不同的值.所以只需删除<E>from Nodeclass声明:

private class Node{
    // the rest
}
Run Code Online (Sandbox Code Playgroud)