Hashcode implementation for custom class in Java

Possible duplicate:
Overriding peers and hashCode in Java

I have to use hashcode and equals for Custom Person. Man consists of

Firstname

Lastname

I have to use equals and hashcode so that two people with firstname and lastname should return true for equals and should be accepted by Hashmap. I implemented the Person class as follows:

public class Person { String firstname; String lastname; public Person(String firstname, String lastname) { this.firstname = firstname; this.lastname = lastname; } @Override public int hashCode() { // TODO Auto-generated method stub return firstname.hashCode()+lastname.hashCode(); } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub Person u=(Person) obj; return u.firstname.equals(firstname) && u.lastname.equals(lastname); } } 

Is the Hashcode implementation correct here? Despite the fact that I get the expected result, I want to know if this implementation is correct?

+6
source share
4 answers

There is a small problem with your equals method, because it will throw an exception if obj is null or not Person , so you should add the following to the top of your peers:

 if(obj==null || !(obj instanceof Person)) return false; 
+4
source

There is an excellent discussion on the correct implementation of equals and hashCode here :

Whenever a.equals (b), then a.hashCode () should be the same as b.hashCode ()

This is the only rule that matters. There is no proper implementation of hashCode beyond this one rule. There are better and worse hash codes in terms of performance and hash collisions, but that's a completely different topic.

Your code looks correct according to this rule, because if a.equals(b) , then firstname.hashCode()+lastname.hashCode() should be the same value for a and b .

+4
source

hashCode() is correct in the sense that it will work (assuming that the firstname and lastname strings are not null), that is, the method will return int . Whether this is a good solution or not, this is a much longer story, which I'm sure you can check the use of the search field above;)

Here's an interesting question I asked for some time regarding hashCode() user implementations: Using a larger prime as a factor when overriding hashCode ()

0
source

Your code is ok. A string has a good hashing algorithm, and just adding hashes is the most efficient way to hash multiple strings in Java.

0
source

All Articles