Duplicate field error while converting a class to generic in Java

302 views Asked by At

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

2

There are 2 answers

0
rzwitserloot On BEST ANSWER

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.

0
Inanc Cakil On
public class LinkedList<E> {
    Node<E> head;

    void add(E data) {
        Node<E> toAdd = new Node<E>(data);
        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;
    }

    public static class Node<E> {
        E data;
        Node<E> next;

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

}

Try this. The constructor doesn't get the type.