Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can getters be used in equals and hashcode?

Tags:

java

I have below code which overrides equals() and hashcode() methods.

public boolean equals(Object obj)
 {
   if (obj == null)
     return false;
   if (!(obj instanceof Name))
     return false;
   Name name = (Name) obj;
   return this.name.equals(name.name);
 }

 public int hashCode()
 {
   return name.hashCode();
 }

here can i replace below 2 lines:

return this.name.equals(name.name);
return name.hashCode();

with

return this.getName().equals(name.getName());
return getName().hashCode();

i mean instead of using properties can i directly use getters inside equals and hashcode methods?

Thanks!

like image 447
user1016403 Avatar asked Apr 09 '12 10:04

user1016403


People also ask

What happens if we do not override hashCode () and equals () in HashMap?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

Is it necessary to override hashCode and equals method?

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.

What is the hashCode () and equals () used for?

The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.

What is contract between equals and hashCode?

The Contract Between equals() and hashcode()If two objects are equal according to the equals(Object) method, then calling the hashcode() method on each of the two objects must produce the same integer result.


1 Answers

Yes sure you could use this,

hashcode() and equals() are field methods, They can access private members directly, but what if there is some logic wrapped in accessor method, so it is always safe to access fields using accessor methods

like image 151
jmj Avatar answered Oct 10 '22 02:10

jmj