【发布时间】:2015-11-25 21:48:41
【问题描述】:
我正在尝试在 java 中实现 LinkedList。结构简单:控制器(BList类),节点,节点的信息组件。
现在我想整合泛型的使用:节点的信息组件应该是泛型的。
我无法理解以下错误。如果我指定了泛型类型<E>,为什么编译器需要 Object 类型?
Test.java:7: error: cannot find symbol
System.out.println(newNode.getElement().getUserId());
^
symbol: method getUserId()
location: class Object
1 error
这是我的代码。提前感谢您的帮助。
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());
}
}
【问题讨论】:
-
只是一个想法:在 BList 实现中,您似乎将 Node 类作为包私有而将头节点作为私有。那么为什么要返回在插入方法中创建的节点呢?这不是暴露 BList 的内部表示吗?
标签: java generics linked-list