我提供了一个接口来与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