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):
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:
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?
提供from
和to
有一个合理hashCode()
实现,您的解决方案是好的。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.