Java 中 == 和 equals() 的区别是什么? [英] What is the difference between == and equals() in Java?

查看:28
本文介绍了Java 中 == 和 equals() 的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想澄清一下我是否理解正确:

I wanted to clarify if I understand this correctly:

  • == 是引用比较,即两个对象都指向同一个内存位置
  • .equals() 计算对象中值的比较
  • == is a reference comparison, i.e. both objects point to the same memory location
  • .equals() evaluates to the comparison of values in the objects

推荐答案

一般来说,您的问题的答案是是",但是...

In general, the answer to your question is "yes", but...

  • .equals(...) 只会比较它所写的比较,不多也不少.
  • 如果一个类没有覆盖equals方法,那么它默认为覆盖这个方法的最近父类的equals(Object o)方法.
  • 如果没有父类提供覆盖,则它默认为来自最终父类 Object 的方法,因此您将使用 Object#equals(Object o) 方法.根据对象 API,这与 == 相同;也就是说,它返回真当且仅当两个变量都引用同一个对象,如果它们的引用是一个并且相同.因此,您将测试对象相等性,而不是功能相等性.
  • 如果您覆盖了 equals,请务必记住覆盖 hashCode,以免破坏合同".根据 API,两个对象的 hashCode() 方法返回的结果必须相同,如果它们的 equals 方法表明它们是相等的.反过来,不一定是正确的.
  • .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 show that they are equivalent. The converse is not necessarily true.

这篇关于Java 中 == 和 equals() 的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆