Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing `hashCode()` for very simple classes

Tags:

java

hashcode

I have a very simple class with only one field member (e.g. String). Is it OK to implement hashCode() to simply return fieldMember.hashCode()? Or should I manipulate the field's hash code somehow? Also, if I should manipulate it, why is that?

like image 653
Hosam Aly Avatar asked Jan 30 '09 19:01

Hosam Aly


People also ask

Do all Java classes have a hashCode method?

Java equals() and hashCode() methods are present in Object class. So every java class gets the default implementation of equals() and hashCode().

What is the default implementation for the hashCode method?

Uses of hashCode() and equals() Methods Its default implementation simply checks the object references of two objects to verify their equality. By default, two objects are equal if and only if they are refer to the same memory location. Most Java classes override this method to provide their own comparison logic.

What makes a good hashCode?

equals , must have the same hashCode. hashCode values should be spread as evenly as possible over all ints. hashCode should be relatively quick to compute. hashCode must be deterministic (not random).


1 Answers

If fieldMember is a pretty good way to uniquely identify the object, I would say yes.

like image 148
bobwienholt Avatar answered Sep 29 '22 12:09

bobwienholt