【发布时间】:2017-04-07 02:39:24
【问题描述】:
我做了这个代码:
import java.util.LinkedList;
public class Node<T> {
private T data;
private LinkedList<T> children;
public Node(T data) {
this.data = data;
this.children = new LinkedList<T>();
}
public T getData() {
return this.data;
}
public LinkedList<T> getChildren(){
return this.children;
}
}
public class Graph <T> implements Network<T> {
private Node source;
private Node target;
private ArrayList<Node> nodes = new ArrayList<Node>();
public Graph(T source,T target) {
this.source = new Node(source);
this.target = new Node(target);
}
public T source() {
return source.getData();
}
public T target() {
return target.getData();
}
我在 source() 和 target() 上得到这个错误: required T found java.lang.Object 为什么? getData() 函数的返回类型是 T(generic type of return)
【问题讨论】:
-
编译器应该如何知道它们是相同的
T?您必须这样明确声明:Node<T> source; Node<T> target; -
@Obicere 谢谢它的工作原理!
-
@HKing Tom 更深入一点,但也得到了相同的观点。你应该接受它作为帮助其他人解决这个问题的答案。