Can getters be used on equal and hash codes?

I have the code below that overrides the 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 I can replace below two lines:

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

from

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

Does i mean that instead of using properties, can i directly use getters inside peers and hash code methods?

Thanks!

+6
source share
5 answers

You can, but why do you? Option A: the compiler encloses the lines, so you still get a link to the field. Option B: the compiler does not make a call, i.e. You have entered one additional method call.

There are also implications for readability - if the name field is available directly in the class, why not reference it directly? It’s easier for me to read, but some people find this inconsistent.

+1
source

Yes sure you can use this,

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

+3
source

Yes, I highly recommend using getters in the implementation of equals() & hashCode() . And, as far as I know, this will not hurt anyone.

Implementing equals() without getters will not give you the correct result when comparing two proxied objects.

For example: if you try to compare two proxy objects returned by your base sleeping tao, you will never get true from your equals() method, even if they are the same objects.

Update

Use getter methods instead of direct access. This is because the instance of the object, since the other may be a proxy object, and not an actual example. To initialize this proxy, you need to access the getter.

This is an excerpt from Effective Java. See this one for more information.

+1
source

Yes, why don't you succeed?

In the future, with such things, I recommend that you just try and see.

0
source

Yes, you can. Why not? What are your doubts?

0
source

Source: https://habr.com/ru/post/912745/


All Articles