This is about objects.
Since these are not primitives, == does not compare what they are. == compares where they are (in the heap memory).
.equals() should (if implemented) compare what is contained in this memory.
This is a part that is easily forgotten, because small lines and numbers in a box often do not receive new memory when creating, because it is more optimal, instead it indicates a cached version of the same. Thus, you can again and again ask for a new โBobโ and simply pass the link (memory address) to the same โBobโ. This makes us compare them as primitives, since it looks like the same thing. But not every object will have this happen to him, so it is a bad habit to allow yourself to develop.
This trick only works if 1) the corresponding object already exists, 2) it is immutable, so you cannot surprise users with other โcopiesโ by changing it.
To abuse the old metaphor, if two people have the same address, itโs safe to bet that they keep the same things at home, as this is the same house. However, just because two people have different addresses, this does not mean that they do not support the same things at home.
The implementation of .equals() is to determine what we care about when comparing what is stored in these objects.
So only trust == to compare primitive values. Use .equals() to ask the object what it believes it is equal to.
Also, this is not just a problem with Java. Each object-oriented language that allows you to directly process primitives and object references / pointers / memory addresses will force you to deal with them differently because the object reference is not an object that it is.
Objects The value does not match the identifier . If there was only one copy of the object with the same contents. Since language cannot fully do this, you are stuck dealing with these two concepts in different ways.
Candyiedrange
source share