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
You don't include the generics in the constructor. It's just:
The E in:
static class Node<E> {}declares the variable. it's like thefooinint foo;. All other places (well, exceptpublic 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 thatEis a thing more than once. You don't need to restateint foo;everytime you use it, either: You only do that once.