Browse - Programming Tips - Java: make hashCode

Date: 2018nov14
Language: Java
Keywords: key, HashSet, HashMap

Q.  Java: make hashCode

A.	This is the usual way.

class MyClass { int mOne; int mTwo; int mThree; @Override public int hashCode() { // Make a lossy sum of all your members int result = 1; final int PRIME = 31; result = PRIME * result + mOne; result = PRIME * result + mTwo; result = PRIME * result + mThree; return result; } // Here's another way (less efficient) @Override public int hashCode() { // Use String.format() to make a string, then take the hashCode() of the string return String.format("%d.%d.%d", mOne, mTwo, mThree).hashCode(); } }