Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
Failure to override one of them while overriding other will result in inconsistent working of hash-based collections..
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Person guest = (Person) obj;
return id == guest.id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + id;
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
These methods are usually overridden when you want to use objects of that type as keys in data structures like hashtables.
- remus.sinorchian November 13, 2013Whenever overriding the equals method is recommended to also override the hashCode method. That is because there must be a relationship between these two methods: equal objects must have equal hash codes, but non-equal objects can have the same hash code.
If the methods are not overridden , then using them as keys in a hashtable is practically impossible (inefficient). By default equals returns true if the two reference variables refer to the same object , and hashCode returns different hash codes for different objects.