user1016403 user1016403 - 25 days ago 17
Java Question

can getters be used in equals and hashcode?

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!

Answer

You can, but why would you? Option A: the compiler inlines that, so you end up with a reference to the field anyway. Option B: The compiler does not inline the call, i.e. you've introduced one extra method call.

There are also implications for legibility- if the name field is directly accessible within the class, why not refer to it directly? I find this easier to read, but some people find it inconsistent.

Comments