[英]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.