我提供了一個接口來與JGraphT一起工作。我的預期用途就像Comparable
,因爲實現Comparable
允許對象與某些數據結構一起使用。同樣,我有一個JGraphT函數,我想要使用任何Distanceable
。Java:接口和泛型的簡單問題
public interface Distanceable<E> {
/**
* A representation of the distance between these two objects.
* If the distance between a0 and a1 is undefined, <code>a0.hasEdge(a1)</code> should return false;
* @param o
* @return
*/
public int distance(E o);
/**
* Are these two objects connected?
* @param o
* @return True if the two objects are connected in some way, false if their distance is undefined
*/
public boolean hasEdge(E o);
}
這是我JGraphtUtilities中的JGraphT函數。它不是Animal
定義,但對於Distanceable
:
public static <E extends Distanceable> WeightedGraph<E, DefaultWeightedEdge> graphOfDistances(Set<E> nodes) {
WeightedGraph<E, DefaultWeightedEdge> g = new SimpleWeightedGraph<E, DefaultWeightedEdge>(DefaultWeightedEdge.class);
for (E a : nodes) {
g.addVertex(a);
}
for (E a : nodes) {
for (E a1 : nodes) {
if (a.hasEdge(a1)) {
g.addEdge(a, a1);
g.setEdgeWeight(g.getEdge(a, a1), a.distance(a1));
}
}
}
return g;
}
但它不工作。編譯器產生一個錯誤在此行中調用此方法的另一個類:
WeightedGraph<Animal, DefaultWeightedEdge> graphOfAnimals = JGraphtUtilities.graphOfAnimals(zoo);
的錯誤是:
The method graphOfAnimals(Set<Animal>) is undefined for the type JGraphtUtilities
然而,
public class Animal implements Distanceable<Animal> {
什麼我錯在這裏做什麼?
另一個問題:編譯器給出了這樣的警告:
Distanceable is a raw type. References to generic type Distanceable<E> should be parameterized.
什麼類型我想給它,如果我想這個功能與所有Distanceable
對象的工作?
你能向我們展示JGraphtUtilitie嗎?它是否有方法graphOfAnimals(Set)? –
2009-12-02 20:32:52
您包含的方法稱爲graphOfDistances(設置節點)而不是graphOfAnimals(設置)。你是否期待編譯器猜測你實際想調用什麼方法? –
2009-12-02 20:40:05