I wanted to clarify if I understand this correctly:
==
-> is a reference comparison, i.e. both objects point to the same memory location.equals()
-> evaluates to the comparison of values in the objects
Am I correct in my understanding ?
I wanted to clarify if I understand this correctly:
==
-> is a reference comparison, i.e. both objects point to the same memory location.equals()
-> evaluates to the comparison of values in the objectsAm I correct in my understanding ?
Also note that
.equals()
normally contains==
for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.And
==
actually does look at values for primitive types, for objects it checks the reference.Just remember that
.equals(...)
has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum
You will never have more than one instance of
A
at a time, and the same forB
andC
. This means that you can actually write a method like so:And you will have no problems whatsoever.
When you evaluate the code, it is very clear that (==) compares according to memory address, while equals(Object o) compares hashCode() of the instances. That's why it is said do not break the contract between equals() and hashCode() if you do not face surprises later.
The String pool (aka interning) and Integer pool blur the difference further, and may allow you to use
==
for objects in some cases instead of.equals
This can give you greater performance (?), at the cost of greater complexity.
E.g.:
Complexity tradeoff: the following may surprise you:
I advise you to stay away from such micro-optimization, and always use
.equals
for objects, and==
for primitives:There are some small differences depending whether you are talking about "primitives" or "Object Types"; the same can be said if you are talking about "static" or "non-static" members; you can also mix all the above...
Here is an example (you can run it):
You can compare the explanations for "==" (Equality Operator) and ".equals(...)" (method in the java.lang.Object class) through these links: