简体   繁体   中英

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. 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):

  1. e1.from() == e2.from() && e1.to() == e2.to() or
  2. 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:

  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.

My general question: Is this a good way to override hashCode() in this situation?

提供fromto有一个合理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.

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