在 Java 中,想要创建一个包含相等顶点/边的简单图(未加权、无向图,不包含图循环或多条边)。
我有两个 Java 类,一个用于顶点:
class Vertex {
private int field;
public Vertex(int field) {
this.field = field;
}
@Override
public boolean equals(Object obj) {
if (obj.getClass().getPackage()
.equals(this.getClass().getPackage())
&& obj.getClass().getName()
.equals(this.getClass().getName())) {
Vertex vertex = (Vertex) obj;
if (this.field == vertex.field)
return true;
}
// Else
return false;
}
@Override
public int hashCode() {
// No need for a perfect hash
return this.field;
}
}
还有一个边缘类:
class Edge {
private int field;
public Edge(int field) {
this.field = field;
}
@Override
public boolean equals(Object obj) {
if (obj.getClass().getPackage()
.equals(this.getClass().getPackage())
&& obj.getClass().getName()
.equals(this.getClass().getName())) {
Edge edge = (Edge) obj;
if (this.field == edge.field)
return true;
}
// Else
return false;
}
@Override
public int hashCode() {
// No need for a perfect hash
return this.field;
}
}
我目前使用JGraphT 库。IllegalArgumentException: "loops not allowed"
但是我在启动这段代码后遇到了:
// Define a EdgeFactory
EdgeFactory<Vertex, Edge> BOND_FACTORY = new EdgeFactory<Vertex, Edge>() {
@Override
public Edge createEdge(Vertex sourceVertex, Vertex targetVertex) {
return new Edge(2);
}
};
// Create the graph
SimpleGraph<Vertex, Edge> graph = new SimpleGraph<Vertex, Edge>(
BOND_FACTORY);
// Create vertexes
Vertex v1 = new Vertex(1);
Vertex v2 = new Vertex(1);
// Add them to the graph
graph.addVertex(v1);
graph.addVertex(v2);
graph.addEdge(v1, v2);
问题是我尝试添加v2
到图表中,但因为v1.equals(v2) == true
v2
从未添加到图表中。来自 lib 的 JavaDoc:
如果指定的顶点尚不存在,则将其添加到该图中。更正式地说,如果该图不包含满足 u.equals(v) 的顶点 u,则将指定的顶点 v 添加到该图中。
此检查在此处实施。
但是,我该如何完成我想要做的事情呢?我可以在这个库中使用另一个实现,还是改变equals()
方法是个好主意?