链表Java结构(泛型)
我正在尝试用java实现LinkedList。结构很简单:控制器(BList类)、节点、节点的信息组件。
现在我想集成泛型的使用:节点的信息组件应该是泛型的。
我不能理解下面的错误。如果我指定了泛型类型<E>
,为什么编译器需要对象类型
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());
}
}
# 1 楼答案
您在两个地方使用
Node
的原始形式:BList
的insert
方法的返回类型。返回一个Node<E>
而不是一个Node
李>Node<Element>
,而不是Node
李>因为使用了原始形式的
Node
,所以Object
现在是返回类型,它没有getUserId
方法。预泛型代码(在Java 1.5之前)会在调用getUserId
之前将getElement
的结果强制转换为Element
,但进行上述更改是解决泛型问题的方法