From 11acb09fe3a451a1f582a9ff67d50edd5c132451 Mon Sep 17 00:00:00 2001 From: Saurav Bhattacharya Date: Tue, 24 Mar 2026 02:49:45 -0700 Subject: [PATCH] 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] --- Gvisual/src/gvisual/Edge.java | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Gvisual/src/gvisual/Edge.java b/Gvisual/src/gvisual/Edge.java index 7aa806a..40afe56 100644 --- a/Gvisual/src/gvisual/Edge.java +++ b/Gvisual/src/gvisual/Edge.java @@ -151,6 +151,49 @@ public boolean isActiveDuring(long start, long end) return edgeStart <= end && edgeEnd >= start; } + /** + * Two Edges are equal if they connect the same vertices (in either order), + * have the same type, and the same weight. + */ + @Override + public boolean equals(Object obj) + { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Edge other = (Edge) obj; + if (Float.compare(weight, other.weight) != 0) return false; + if (!java.util.Objects.equals(edgeType, other.edgeType)) return false; + // Undirected: (v1,v2) == (v2,v1) + boolean sameOrder = java.util.Objects.equals(vertex1, other.vertex1) + && java.util.Objects.equals(vertex2, other.vertex2); + boolean reverseOrder = java.util.Objects.equals(vertex1, other.vertex2) + && java.util.Objects.equals(vertex2, other.vertex1); + return sameOrder || reverseOrder; + } + + /** + * Hash code consistent with {@link #equals}: order-independent on vertices. + */ + @Override + public int hashCode() + { + // Use addition so vertex order doesn't matter + int vertexHash = (vertex1 == null ? 0 : vertex1.hashCode()) + + (vertex2 == null ? 0 : vertex2.hashCode()); + return 31 * (31 * vertexHash + (edgeType == null ? 0 : edgeType.hashCode())) + + Float.floatToIntBits(weight); + } + + /** + * Human-readable representation: "Edge[v1--v2, type=f, weight=1.0]". + */ + @Override + public String toString() + { + return String.format("Edge[%s--%s, type=%s, weight=%.1f]", + vertex1, vertex2, edgeType, weight); + } + }