メソッドが定義されている場合、Javaのジェネリックは、エラーを投げます

MetallicPriest:

私はJavaでジェネリックを学んでいます。そのために、私はそのような単純なLinkedListのを試してみました。

class Node {
  private int age;
  private String name;
  private Node next;

  public Node(int age, String name) {
    this.age = age;
    this.name = name;
    this.next = null;
  }

  public int getAge() {
    return this.age;
  }

  public String getName() {
    return this.name;
  }

  public Node getNext() {
    return this.next;
  }

  public void setNext(Node next) {
    this.next = next;
  }
}

class LinkedList<T> {
  private T head;
  private T current;

  public LinkedList() {
    head = null;
    current = null;
  }

  public void append(T x) {
    if (head == null) {
      head = x;
      current = x;
    }
    else {
      current.setNext(x);
      current = x;
    }
  }

  public T getAt(int index) {
    T ptr = head;
    for(int i = 0; i < index; i++) {
      ptr = ptr.getNext();
    }
    return ptr;
  }
}

class Main {
  public static void main(String[] args) {
    LinkedList<Node> list = new LinkedList<Node>();
    list.append(new Node(39, "John"));
    list.append(new Node(43, "Josh"));
    Node x = list.getAt(1);
    System.out.println(String.format("%d, %s", x.getAge(), x.getName()));
  }
}

すべてのメソッドは、Nodeクラスに存在する操作を行いながら、しかし、私は、このエラーが発生します。私は何の間違いでしょうか?

LinkedList.java:16: error: cannot find symbol
      current.setNext(x);
             ^
  symbol:   method setNext(T)
  location: variable current of type T
  where T is a type-variable:
    T extends Object declared in class LinkedList
LinkedList.java:24: error: cannot find symbol
      ptr = ptr.getNext();
               ^
  symbol:   method getNext()
  location: variable ptr of type T
  where T is a type-variable:
    T extends Object declared in class LinkedList
2 errors
彼らは次のとおりでした:

場合currentタイプのものでありT、あなたはのメソッドを呼び出すことはできませんNodeクラス(などsetNext()の)をcurrentするので、Tあなたはあなたのをインスタンス化するとき、任意のクラスによって置換することができますLinkedList

あなたのNodeクラスはのジェネリック型引数であってはなりませんLinkedListAはLinkedList常にで作られるべきNode秒。それぞれに格納されるデータのタイプは、Node一般的なタイプでなければなりません。

class Node<T> {
  private T data;
  private Node next;

  public Node(T data) {
    this.data = data;
    this.next = null;
  }
}

そして、LinkedList含まれている必要がありNode<T>、ノードを:

class LinkedList<T> {
  private Node<T> head;
  private Node<T> current;
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=333842&siteId=1