Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic hash codes in Java [closed]

Tags:

java

hashcode

I am somewhat new to Java. Is there is a hashcode utility class that can generate a good hash code for a generic object with members of arbitrary types inside the class? Can I recursively step through the instance of a generic java object and accumulate a hash code that guarantees two equal objects of this class will always compute the same hash code? The context of this question is Android and the Objects.hashCode() etc is not available to me in the Java version I am using (and I have no option to migrate to a newer version). I am guessing the answer is no based on what I have seen so far.

like image 704
user2399453 Avatar asked Dec 06 '22 00:12

user2399453


1 Answers

Since Java 7, you have Objects.hash()

return Objects.hash(this.foo, this.bar, this.baz);

it also helps implementing equals:

return Objects.equals(this.foo, o.foo)
       && Objects.equals(this.bar, o.baz)
       && Objects.equals(this.baz, o.baz)
like image 194
JB Nizet Avatar answered Dec 26 '22 09:12

JB Nizet