不兼容的类型泛型Java

时间:2017-04-07 02:39:25

标签: java generics

我做了这段代码:

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()上得到这个错误:需要T找到java.lang.Object为什么? getData()函数返回的类型是它的T(泛型返回值)

2 个答案:

答案 0 :(得分:3)

private Node source;
private Node target;

这些应该是Node<T>。同样,以下几行。编译器会给你一个警告。记下它。 (当混合原始类型和泛型时,Java语言规范通常要求编译器放弃。)

答案 1 :(得分:0)

Node替换为Node<T>班级中的Graph

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();
    }
}