Programming Tips - Java 7+: Easy way to implement hashCode()

Date: 2020apr14 Update: 2025oct3 Language: Java Q. Java 7+: Easy way to implement hashCode() A. Use the Objects.hash() utility function which was introduced in Java 7+ (Android level 19 if you are developing for that platform) Full example:
import java.util.Objects; class Demo { static class MyClass { int x; float y; String z; @Override public int hashCode() { return Objects.hash(x, y, z); } } public static final void main(String []args) { MyClass obj = new MyClass(); System.out.println("hash=" + obj.hashCode()); } }
Output:
hash=29791
As you can see it takes any kind of variable. It calls hashCode() on all then hashes the result. Records in Java 14+ avoid this altogether.