Java基础 equals()、hashCode()和 == 区别

在说这些的比较前,必须先要声明一些约定,违法了约定,谈他们的区别简直是不可理喻。

1. hashCode()设计原则

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer。
    一致性。一个对象的hashCode()始终一样。

  2. If two objects are equal according to the equals(Object)
    method, then calling the hashCode method on each of the two objects must produce the same integer result.
    如果两个对象相同,那么他们的hashcode应该 相等。

  3. It is not required that if two objects are unequal according to the equals() method, then calling the hashCode method on each of the two objects must produce distinct integer results.
    如果两个对象不相同,他们的hashcode可能相同。

  4. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
    最好的做法是,不同对象的hashCode()值是不一样的。这取决于JVM对内存地址进行转化的实现。

2. 复写equals()方法遵守的约定

  1. 自反性: 对象必须等于其自身 A == A为true
  2. 对称性: 如果A==B为true,则B == A也为true
  3. 传递性: 如果A==B,B==C,那么则有A==C
  4. 一致性: 如果两个对象相等,它们就始终保持相等
  5. 非空性: 所有对象都必须不等于null。

因为没有覆盖hashCode()方法违法了hashCode的第二条约定:相等对象必须具有相等的散列码。

3. 结论

  1. 如果两个对象equals,Java运行时环境会认为他们的hashcode一定相等。
  2. 如果两个对象不equals,他们的hashcode有可能相等。
  3. 如果两个对象hashcode相等,他们不一定equals。
  4. 如果两个对象hashcode不相等,他们一定不equals。

4. “==”

== 操作符比较的是对象内存地址。
单例、相同的枚举都返回true。


参考:
JDK文档:
[ hashCode() 和equals() 区别和作用](http://blog.csdn.net/lclai/article/details/6195104)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

baiiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值