2017-04-07 102 views
3

我這樣做代碼:不兼容的泛型類型的Java

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

我得到源()和目標這個錯誤():需要t上找不到java.lang.Object繼承爲什麼呢?的getData()函數的返回類型是T(通用型回報)

+0

更換NodeNode<T>可能是重複的http://計算器。 com/questions/4121179/casting-objects-to-t-type – Avi

+1

編譯器應該如何知道它們是相同的'T'?你必須明確地聲明它:'節點源;節點目標;' – Obicere

+0

@Obicere感謝它的工作! – HKing

回答

3
private Node source; 
private Node target; 

這些應該是Node<T>。同樣在以下幾行中。編譯器會給你一個警告。記下它。 (當你拌生類型和泛型,Java語言規格往往需要編譯器就放棄了。)

0

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