1
我定義含有GraphNode類圖形如下,我打算用於聲明N是比較使用泛型2個GraphNode對象。實例化遞歸地定義複合一般類在Java
的問題是,我應如何實例化的遞歸綁定的圖表。而如下聲明
錯誤。
Graph<Integer,Comparable<GraphNode>> graph = new Graph<>();
綁定不匹配:類型Comparable<GraphNode>
不是類型Graph<T,N>
public class Graph<T, N extends Comparable<GraphNode<T, N>>> {
private N root;
private Class<N> clazz;
Graph(Class<N> clazz) {
this.clazz = clazz;
}
public N getInstance() {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings("unchecked")
public void insert(T d, N n) {
if (root == null && n == null)
root = getInstance();
if (root == null)
root = n;
N node = root;
while (node != null) {
if (node.equals(n)) {
N newNode = getInstance();
((GraphNode<T, N>) newNode).setAdjNode(newNode);
}
}
}
}
public class GraphNode<T, N extends Comparable<GraphNode<T, N>>> implements Comparable<N> {
private T data;
private LinkedHashSet<N> adjNodes = new LinkedHashSet<>();
GraphNode() {
data = null;
}
GraphNode(T d) {
setData(d);
}
public void setAdjNode(N n) {
adjNodes.add(n);
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public int hashCode() {
return data.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof GraphNode<?, ?>) {
return ((GraphNode<?, ?>) obj).getData() == this.getData();
}
return false;
}
@Override
public String toString() {
return data + "";
}
@Override
public int compareTo(N o) {
return this.compareTo(o);
}
}
什麼完整的錯誤信息? –
@JimGarrison更新了問題。 – Curious