我使用 jgrapht 库创建了一个有向图,我的顶点是我用以下代码创建的 Point 对象:
public static class Point {
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public String toString() {
return ("[x="+x+" y="+y+"]");
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + this.x;
hash = 71 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object other)
{
if (this == other)
return true;
if (!(other instanceof Point))
return false;
Point otherPoint = (Point) other;
return otherPoint.x == x && otherPoint.y == y;
}
}
我可以使用 successorListOf() 检索顶点的后继者,并使用前驱者ListOf() 检索其前任者。
我想在顶点的前驱和后继之间添加边(在我的例子中,总是只有一个前驱,但有许多后继)。所以我想做这样的事情:
directedGraph.addEdge(Graphs.predecessorListOf(directedGraph,myPoint),Graphs.successorListOf(directedGraph,myPoint));
但是这些方法不采用顶点列表作为参数,一次仅采用一个顶点。 我认为我应该做的是自动为每个后继者和前任者创建一个 Point 对象,但这似乎不合适,因为这些元素已经是顶点,所以它们也是 Point 对象。
我该怎么做?我不知道如何根据后继者或前任列表创建对象。这是处理这个问题的正确方法吗?
最佳答案
我不知道 jgrapht 库,但你不能简单地循环前驱点和后继点列表吗:
for (Point predecessor : Graphs.predecessorListOf(directedGraph, myPoint)) {
for (Point successor : Graphs.successorListOf(directedGraph, myPoint)) {
directedGraph.addEdge(predecessor, successor);
}
}
关于java - 根据列表元素自动创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31797791/