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 ?
In general, the answer to your question is "yes", but...
.equals(...)
will only compare what it is written to compare, no more, no less.equals(Object o)
method of the closest parent class that has overridden this method.Object#equals(Object o)
method. Per the Object API this is the same as==
; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.hashCode
if you overrideequals
so as not to "break the contract". As per the API, the result returned from thehashCode()
method for two objects must be the same if theirequals
methods show that they are equivalent. The converse is not necessarily true.Both == and .equals() refers to the same object if you don't override .equals().
Its your wish what you want to do once you override .equals(). You can compare the invoking object's state with the passed in object's state or you can just call super.equals()
==
is an operator andequals()
is a method.Operators are generally used for primitive type comparisons and thus
==
is used for memory address comparison andequals()
method is used for comparing objects.----Output----- true false true
The major difference between == and equals() is
1) == is used to compare primitives.
For example :
2) equals() is used to compare objects. For example :
== operator always reference is compared. But in case of
it's depends's on implementation if we are overridden equals method than it compares object on basic of implementation given in overridden method.
in above code both obj and obj1 object contains same data but reference is not same so equals return false and == also. but if we overridden equals method than
know check out it will return true and false for same case only we overridden
it compare object on basic of content(id) of object
still compare references of object.