Java:Interfaces和Generics的简单问题

时间:2009-12-02 20:26:17

标签: java generics interface comparable

我创建了一个与JGraphT一起工作的界面。我的预期用途类似于Comparable,因为实现Comparable允许对象与某些数据结构一起使用。 Simiarly,我有一个JGraphT函数,我希望使用Distanceable的任何东西。

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个对象,我想给它什么类型?

1 个答案:

答案 0 :(得分:2)

  

方法graphOfAnimals(Set<Animal>)   未定义类型   JGraphtUtilities

您在代码示例中显示的方法是graphOfDistances。 问题在于方法graphOfAnimals。所以......

您有graphOfAnimals方法在Set<Animal>课程中占用JGraphtUtilities吗?