I’m working on a graph library in Java (https://github.com/aisthesis/java-graph2012 for full context) and need to override hashCode() for a WeightedEdge class in which edges are not directed. That is, I have my equals() override method set up so that for 2 weighted edges e1 and e2, they are equal if one of the following conditions hold (the from() and to() methods return tail and head vertex of the edge):
- e1.from() == e2.from() && e1.to() == e2.to() or
- e1.from() == e2.to() && e1.to() == e2.from()
In another context, I want to create a HashSet of weighted edges, and I end up getting duplicate edges unless I also override the hashCode() method in such a way as to be consistent with my equals() override.
So, here’s my simple solution (where I haven’t interfered with Java’s default hashCode() for my Vertex class and from and to refer to Vertex objects):
@Override
public int hashCode() {
return from.hashCode() + to.hashCode();
}
My reasoning:
- It’s efficient since addition is about as efficient as one can get (I guess one could also xor the 2 hash codes?)
- It’s symmetric, so
reversing from and to will give the same hash code - It will usually
provide distinct hashcodes if a vertex is different.
Point 3 obviously is far from 100%, so part of my question is whether that should matter.
My general question: Is this a good way to override hashCode() in this situation?
Provided
fromandtohave a reasonablehashCode()implementation, your solution is fine.