Skip to content
This repository was archived by the owner on Jun 18, 2026. It is now read-only.

Commit 11acb09

Browse files
refactor: add equals/hashCode/toString to Edge class
The Edge class is used extensively in Sets and Maps throughout the codebase (e.g., ShortestPathFinder, CommunityDetector, GraphStats) but was relying on Object's identity-based equals/hashCode. This meant two Edge objects connecting the same vertices with the same type and weight were not considered equal in collections. - equals: order-independent vertex comparison (undirected edges) - hashCode: consistent with equals, order-independent - toString: readable format for debugging: Edge[v1--v2, type=f, weight=1.0]
1 parent 0be89bb commit 11acb09

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Gvisual/src/gvisual/Edge.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,49 @@ public boolean isActiveDuring(long start, long end)
151151
return edgeStart <= end && edgeEnd >= start;
152152
}
153153

154+
/**
155+
* Two Edges are equal if they connect the same vertices (in either order),
156+
* have the same type, and the same weight.
157+
*/
158+
@Override
159+
public boolean equals(Object obj)
160+
{
161+
if (this == obj) return true;
162+
if (obj == null || getClass() != obj.getClass()) return false;
163+
Edge other = (Edge) obj;
164+
if (Float.compare(weight, other.weight) != 0) return false;
165+
if (!java.util.Objects.equals(edgeType, other.edgeType)) return false;
166+
// Undirected: (v1,v2) == (v2,v1)
167+
boolean sameOrder = java.util.Objects.equals(vertex1, other.vertex1)
168+
&& java.util.Objects.equals(vertex2, other.vertex2);
169+
boolean reverseOrder = java.util.Objects.equals(vertex1, other.vertex2)
170+
&& java.util.Objects.equals(vertex2, other.vertex1);
171+
return sameOrder || reverseOrder;
172+
}
173+
174+
/**
175+
* Hash code consistent with {@link #equals}: order-independent on vertices.
176+
*/
177+
@Override
178+
public int hashCode()
179+
{
180+
// Use addition so vertex order doesn't matter
181+
int vertexHash = (vertex1 == null ? 0 : vertex1.hashCode())
182+
+ (vertex2 == null ? 0 : vertex2.hashCode());
183+
return 31 * (31 * vertexHash + (edgeType == null ? 0 : edgeType.hashCode()))
184+
+ Float.floatToIntBits(weight);
185+
}
186+
187+
/**
188+
* Human-readable representation: "Edge[v1--v2, type=f, weight=1.0]".
189+
*/
190+
@Override
191+
public String toString()
192+
{
193+
return String.format("Edge[%s--%s, type=%s, weight=%.1f]",
194+
vertex1, vertex2, edgeType, weight);
195+
}
196+
154197
}
155198

156199

0 commit comments

Comments
 (0)