[英]Edge of undirected graph in Java
假设我正在编写一个Java类来表示无向图的边缘。 这个类Edge
包含两个顶点to
和from
。
class Edge<Vertex> { private final Vertex to, from public Edge(Vertex to, Vertex from) { this.to = to; this.from = from; } ... // getters, equals, hashCode ... }
显然e1 = new Edge(v1, v2)
在无向图中e1 = new Edge(v1, v2)
和e2 = new Edge(v2, v1)
实际上是相同的。 是否有意义? 您将如何实现Edge
类以满足这一要求?
根据一些唯一的标识符对构造函数中的顶点执行排序。 这样,无论顺序如何,都可以一致地存储它们。
我发现这比noMAD的解决方案更可取,因为与这些对象交互的所有代码将对它们进行相同的对待,而不仅仅是您对equals
的实现。
此外,调用类的成员to
和from
是混乱,因为它听起来像一个有向图。 我将它们重命名为更通用的名称,例如vertex1
和vertex2
。
public Edge(Vertex x, Vertex y) {
if (vertex2.getId() > vertex1.getId()) {
this.vertex1 = x;
this.vertex2 = y;
} else {
this.vertex1 = y;
this.vertex2 = x;
}
}
实际上,我的Edge
类中不会包含这种逻辑,而是某种可监督的类,例如Graph
类。 其原因是因为“ Edge
只是具有两个顶点的对象。 它对图形的其余边缘一无所知。
因此,为了扩展@noMad的答案,我实际上将他的checkIfSameEdge
方法放在我的Graph
类中:
public class Graph {
private List<Edge> edges;
....
public void addEdge(Edge e) {
for (Edge edge : edges) {
if (isSameEdge(edge, e) {
return; // Edge already in Graph, nothing to do
}
edges.add(e);
}
private boolean isSameEdge(Edge edge1, Edge edge2) {
return ((edge1.to.equals(edge2.to) && edge1.from.equals(edge2.from))
|| (edge1.to.equals(edge2.from) && edge1.from.equals(edge2.to)))
}
}
BTW:我会重新命名to
和from
于vertex1
和vertex2
因为它是一个无向图,并和指示方向,但是这只是我的opion。
好吧,在我的头上,最幼稚的方法是:
protected boolean checkIfSameEdge(Vertex to, Vertex from) {
if(to.equals(this.from) && from.equals(this.to) || to.equals(this.to) && from.equals(this.from)) {
return true;
return false;
}
显然,您将必须重写equals
和hashcode
假定节点包含某种标量值-根据这些值对参数进行排序(使用compareTo方法),并使用工厂创建新实例或返回现有实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.