[英]Java hashCode() override for edge class
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. 我正在使用Java中的图形库(https://github.com/aisthesis/java-graph2012获取完整上下文),并且需要为其中未定向边缘的WeightedEdge类重写hashCode()。 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): 也就是说,我设置了equals()重写方法,以便对于2个加权边e1和e2,如果满足以下条件之一,则它们相等(from()和to()方法返回尾部的头尾顶点)边缘):
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. 在另一个上下文中,我想创建一个加权边的HashSet,最终得到重复的边,除非我也以与equals()重写一致的方式重写hashCode()方法。
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): 因此,这是我的简单解决方案(在这里,我没有干扰我的Vertex类的Java默认hashCode()以及from和to引用Vertex对象):
@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. 第三点显然远非100%,所以我的问题之一就是那是否重要。
My general question: Is this a good way to override hashCode() in this situation? 我的一般问题:在这种情况下,这是重写hashCode()的好方法吗?
提供from
和to
有一个合理hashCode()
实现,您的解决方案是好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.