Incompatible Java generics types
I made this code:
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();
}
I am getting this error on source () and target (): required T found java.lang.Object why? return type of getData () function is T (generic return type)
+3
source to share
2 answers
Replace Node
with Node<T>
in classGraph
public class Graph<T> implements Network<T> {
private Node<T> source;
private Node<T> target;
private ArrayList<Node> nodes = new ArrayList<Node>();
public Graph(T source, T target) {
this.source = new Node<T>(source);
this.target = new Node<T>(target);
}
public T source() {
return source.getData();
}
public T target() {
return target.getData();
}
}
0
source to share