javagenericslinked-listgeneric-programming

Duplicate field error while converting a class to generic in Java


I wrote a code to implement linked lists in java but when I converted it into a generic class I got a bunch of errors.

public class LinkedList<E> {
static class Node<E> {
    E data;             //encountering error here - "Duplicate field LinkedList.Node<E>.data"
    Node<E> next;

 public Node<E>(E data){   // error - Syntax error on token ">", Identifier expected after this token
         this.data = data;
         next = null;
    }
 } 

 Node<E> head;
 void add(E data){
    Node<E> toAdd = new Node<E>(data);   //error - The constructor LinkedList.Node<E>(E) is undefined
    if(head == null){
        head = toAdd;
        return;
    }
    Node<E> temp = head;
    while(temp.next != null){
        temp = temp.next;
    }
    temp.next = toAdd; 
 }

  void print(){
    Node<E> temp = head;
    while(temp != null)
    {
        System.out.print(temp.data + " ");
        temp = temp.next;
    }
  }
  boolean isEmpty(){
    return head == null;
 }

}

The code worked fine when I hadn't made the class generic


Solution

  • You don't include the generics in the constructor. It's just:

    public Node(E data) { ... }
    

    The E in: static class Node<E> {} declares the variable. it's like the foo in int foo;. All other places (well, except public class LinkedList<E>, which declares a completely different type variable with the exact same name - but your Node class is static so that's allright here) are using it. You don't need to re-declare that E is a thing more than once. You don't need to restate int foo; everytime you use it, either: You only do that once.