java 中 == 和 equal() 的区别

1.     Java == vs equals() confusion


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 ?


In general, the answer to your question is “yes”, but…

equals will only compare what it is written to compare, no more, no less.
if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the 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.
Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.


电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>