0

I'm trying to do the hashing the right way (I admit that I usually can be a bit sloppy there, relying on the automagical management). I think I got it under control but I feel uncertain if it's really the fully correct approach or if I'm missing something (yes, I've read quite a few pages on it but still...).

In my class, I have designed something like this. I'm leaving out the definition of Segment intentionally, because I believe that my approach is correct without knowing it.

public class Compound
{
  public Segment PartA { get; set; }
  public Segment PartB { get; set; }
  ...
  public int GetHashCode()
  {
    return PartA.GetHashCode() * PartB.GetHashCode()
  }
}

The method seems to be safe, as the integers won't overflow but instead wrap around the maximum. The advantage of this approach is to me that both parts will actually affect the hash produced.

I wonder though if I should be using multiplication or addition (or something totally else) when computing it. Do I actually gain anything from hashing in both of the parts? I can't really tell.

  • I would see [this](http://stackoverflow.com/a/2730901/1193647) answer for a good way to hash multiple objects together. And see [this answer](http://stackoverflow.com/a/299748/1193647)(linked in the above as well) as to why. – Kolichikov Sep 04 '16 at 18:32

1 Answers1

3

Yes, it makes sence if you want the hash value be determined by both PartA and PartB. In general case it could be something like this:

public int GetHashCode()
{
   // hash must not throw exceptions; check for null:
   if (null == PartA) 
     return null == PartB ? 0 : PartB.GetHashCode();
   else if (null == PartB) 
     return PartA.GetHashCode(); 

   // XOR ^ is a better choice: no integer overflow and no bias
   return PartA.GetHashCode() ^ PartB.GetHashCode();
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    `^` is also better than `*` because if any property ends up having a hash code of 0 it will propagate all the way down and make the end result 0 too. – Scott Chamberlain Sep 04 '16 at 18:33
  • 1
    Note that simple XOR does not work well for cases when you don't know distribution of hash codes (i.e. if properties are integer types with smallish actual range of values). Shifting/multiplying on number first makes much better hash function (some guidance http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml, can't quickly find better one) – Alexei Levenkov Sep 04 '16 at 19:17