2017-04-07 6 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()関数の戻り値の型が、それはこれらがNode<T>あるべきT(戻りのジェネリック型)

+0

Node<T>Nodeを交換してください:// stackoverflowの。 com/questions/4121179/casting-objects-to-t-type – Avi

+1

コンパイラは、それらが同じ 'T'であることをどのように知っていると思われますか?明示的にそれを次のように宣言する必要があります: 'Node source;ノードターゲット; ' – Obicere

+0

@Obicereありがとうございます! – HKing

答えて

3
private Node source; 
private Node target; 

です。同様に、以下の行のうちのいくつかを参照してください。コンパイラから警告が出されます。注意してください。 (あなたは、生の型とジェネリックを混ぜるときは、Java言語仕様は、多くの場合、放棄するコンパイラが必要です。)

0

は、httpの重複ことかもしれませんあなたの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(); 
    } 
} 
関連する問題