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?
Java equals() and hashCode() methods are present in Object class. So every java class gets the default implementation of equals() and hashCode().
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.
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).
If fieldMember is a pretty good way to uniquely identify the object, I would say yes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With