简体   繁体   中英

Incompatible types generics Java

I did 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 get this error on source() and target(): required T found java.lang.Object why? the type of return of getData() function it's T(generic type of return)

private Node source;
private Node target;

These should be Node<T> . Likewise on a few of the following lines. The compiler will have given you a warning. Take note of it. (When you mix raw types and generics, the Java Language Spec often requires the compiler to give up.)

Replace Node with Node<T> in your Graph class

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM