I'm trying to implement a LinkedList in java. The structure is simple: the controller (BList class), the node, the information component of the node.
Now I would like to integrate the use of Generics: the information component of the node should be generic.
I can't understand the following error. Why the compiler expects an Object type if I've specified a generic type <E>?
Test.java:7: error: cannot find symbol
System.out.println(newNode.getElement().getUserId());
^
symbol: method getUserId()
location: class Object
1 error
This is my code. Thanks in advance for you help.
public class BList<E> {
private Node head;
public BList() {
this.head = null;
}
public Node insert(E element) {
Node<E> newNode = new Node<E>(element);
newNode.setSucc(this.head);
this.head = newNode;
return newNode;
}
}
class Node<E> {
private Node succ;
private E element;
public Node(E element) {
this.succ = null;
this.element = element;
}
public void setSucc(Node node) {
this.succ = node;
}
public void setElement(E element) {
this.element = element;
}
public E getElement() {
// return this.element; // ?
return (E) this.element;
}
}
class Element {
private int userId;
public Element(int userId) {
this.userId = userId;
}
public int getUserId() {
return this.userId;
}
}
public class Test {
public static void main(String[] args) {
BList<Element> bList = new BList<Element>();
Node newNode = bList.insert(new Element(1));
// error happens here!
System.out.println(newNode.getElement().getUserId());
}
}