Combining Java hashcodes into a “master” hashcode?

That's the normal practice. It looks pretty reasonable to me. If you're using Eclipse, you should find that it can generate equals and hashCode for you—just check the Source menu.It will do the same thing—enumerate your fields and create an equals method that checks all of them, then choose n prime numbers and do what you've done to create a hashCode method.

Thanks Samir, I didn't know that Eclipse had this. – Nick Wiggill May 31 '10 at 12:24.

The reason for using prime numbers (they don't necessarily have to be "large" prime numbers) is indeed to avoid common factors. Hash codes are used by hash-based collection classes such as HashSet and HashMap. They work best if the hash codes of objects in the map are as dissimilar as possible (they have to do more work to distinguish objects if the hash code of those objects is the same).

Multiplying the hash codes of the parts that you use to make a combined hash code with primes ensures that the parts will not have common factors, so there's less chance of collisions (with regard to the hash codes of different parts overlapping each other).

– Nick Wiggill May 31 '10 at 12:24 I'm not entirely sure; if + were used instead of XOR, then it would be clear - you should use different primes. So I'd do that just to be safe. Note that XOR is almost like adding numbers, but without carrying bits (i.e.1 ^ 1 = 0 and not 10, carrying a bit forward).

I haven't thought through how that exactly will affect the result. – Jesper May 31 '10 at 13:20 @Nick Wiggill I believe the important thing is that the prime being multiplied by not be a factor of the size of the hashTable's underlying array. If you multiply by 17, and the array's size is 34, then all objects will end up at position 0 or 17 (causing lots of collisions).

– ILMTitan Jun 1 '10 at 15:13 There is one main danger of using ^ instead of +. Repeating the same element in a series of ^ will cancel each other out.(N ^ Y ^ N = Y) This is mitigated by the fact that it is being multiplied at every step. – ILMTitan Jun 1 '10 at 15:18.

You can find a sample chapter of Effective Java here which gives a great examples for creating hashCodes, using primes etc.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions