您的位置:首页 > 编程语言 > Java开发

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

2016-10-22 23:44 323 查看
在说这些的比较前,必须先要声明一些约定,违法了约定,谈他们的区别简直是不可理喻。

1. hashCode()设计原则:

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()始终一样。

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应该 相等。

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可能相同。

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()
方法遵守的约定:

自反性: 对象必须等于其自身
A == A为true


对称性: 如果
A==B为true
,则
B == A也为true


传递性:如果
A==B,B==C
,那么则有
A==C


一致性: 如果两个对象相等,它们就始终保持相等

非空性: 所有对象都必须不等于null。

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

3. 结论:

如果两个对象equals,Java运行时环境会认为他们的hashcode一定相等。

如果两个对象不equals,他们的hashcode有可能相等。

如果两个对象hashcode相等,他们不一定equals。

如果两个对象hashcode不相等,他们一定不equals。

4. “==”

==
操作符比较的是对象内存地址。

单例、相同的枚举都返回true。

参考:

JDK文档:

[hashCode() 和equals() 区别和作用](http://blog.csdn.net/lclai/article/details/6195104)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: