我试图在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());
}
}
答案 0 :(得分:4)
您在2个地方使用function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
//the IIFE
(function(i) {
var item = 'item' + i;
result.push(function() {
console.log(item + ' ' + list[i])
});
})(i);
}
return result;
}
function testList() {
var fnlist = buildList([1, 2, 3]);
// Using j only to help prevent confusion -- could use i.
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
testList();
的原始形式:
Node
的{{1}}方法的返回类型。返回BList
而不是insert
。Node<E>
中Node
的声明。将其声明为newNode
而不是main
。由于使用了Node<Element>
的原始格式,Node
现在是返回类型,它没有Node
方法。 pre-generics代码(在Java 1.5之前)会在调用Object
之前将getUserId
的结果转换为getElement
,但进行上述更改是通过泛型解决此问题的方法。 / p>