gpt4 book ai didi

Java:接口(interface)和泛型的简单问题

转载 作者:行者123 更新时间:2023-12-02 08:35:51 24 4
gpt4 key购买 nike

我制作了一个与 JGraphT 一起使用的界面。我的预期用途类似于 Comparable,因为实现 Comparable 允许对象与某些数据结构一起使用。同样,我有一个 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 对象,我想要给它什么类型?

最佳答案

The method graphOfAnimals(Set<Animal>) is undefined for the type JGraphtUtilities

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

你有graphOfAnimals吗?需要 Set<Animal> 的方法在 JGraphtUtilities类?

关于Java:接口(interface)和泛型的简单问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1835560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com