我查看了一下接口文档,里面是这样描述的:
该方法重写了
Collection
接口的
contains
方法
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o == null ? e==null : o.equals(e)).
也就是说,当且仅当
1:参数o,如果o为空,set中也有空时
2:参数o.equals(e),e为set中的一个元素
上述两种情况,会返回true。
同样,阅读接口文档,
equals
方法说明如下:
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes
就是说,如果一个对象重写了
equals
方法,通常也需要重写
hashCode
方法。根据契约约定,如果两个对象相等,则它们的hash值必须相等。
换句话说,如果两个对象的hash值不同,则调用它们的
.equals
去比较,肯定返回
false
。
阅读
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.
如果两个对象相等,则必须返回相等的hash值。这和
equals
说明一致。
It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
简单的说,如果两个对象不相等,它们的hash值可能相等。
所以,不能认为hash值一样,就说两个对象相等。
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.)
通常,不同对象还是需要返回不同的hash值。通常是通过将对象的内部地址转换为integer实现的。
我自定义一个Dog对象,先不重写
equals
和
hashCode
,当Set中添加了两个白色的狗对象时,我们用
contains
方法去校验Set中是否包含白色的狗对象,会得到如下结果: