简体   繁体   English

边缘类的Java hashCode()重写

[英]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()方法返回尾部的头尾顶点)边缘):

  1. e1.from() == e2.from() && e1.to() == e2.to() or e1.from()== e2.from()&& e1.to()== e2.to()或
  2. e1.from() == e2.to() && e1.to() == e2.from() 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. 在另一个上下文中,我想创建一个加权边的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: 我的推理:

  1. It's efficient since addition is about as efficient as one can get (I guess one could also xor the 2 hash codes?) 它之所以有效,是因为加法的效率差不多(我猜一个也可以对两个哈希码进行异或运算?)
  2. It's symmetric, so reversing from and to will give the same hash code 它是对称的,因此从和反转将给出相同的哈希码
  3. 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. 第三点显然远非100%,所以我的问题之一就是那是否重要。

My general question: Is this a good way to override hashCode() in this situation? 我的一般问题:在这种情况下,这是重写hashCode()的好方法吗?

提供fromto有一个合理hashCode()实现,您的解决方案是好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM