Generic in Java throwing errors when methods are defined

MetallicPriest :

I am learning Generics in Java. For that, I tried out a simple LinkedList like that.

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

But I get this error, while all the methods do exist in the Node class. What mistake am I doing?

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
Eran :

If current is of type T, you can't call methods of the Node class (such as setNext()) on current, since T can be substituted by any class when you instantiate your LinkedList.

Your Node class shouldn't be the generic type argument of LinkedList. A LinkedList should always be made of Nodes. The type of the data stored in each Node should be a generic type.

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

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

And the LinkedList should contain Node<T> nodes:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327013&siteId=1