java equals == hashcode

1.首先看看Object 中 equals()方法的实现

 

    public boolean equals(Object obj) {
    return (this == obj);//比较两个对象是否指向同一个地址(引用),其作用同==
    }

 

 再来看看JDK中的说明:

The equals method implements an equivalence relation on non-null object references:(对象的引用)

  • It is reflexive : for any non-null reference value x , x.equals(x) should return true .(自反性,自已和自己比)
  • It is symmetric : for any non-null reference values x and y , x.equals(y) should return true if and only if y.equals(x) returns true .(对称性,一看就明白,不用多说)
  • It is transitive : for any non-null reference values x , y , and z , if x.equals(y) returns true and y.equals(z) returns true , then x.equals(z) should return true .(传递性,也不用多说了,呵呵)
  • It is consistent : for any non-null reference values x and y , multiple invocations of x.equals(y) consistently return true or consistently return false , provided no information used in equals comparisons on the objects is modified.(一致性,参比的对象没有改变,比较的结果也不会变化)
  • For any non-null reference value x , x.equals(null) should return false .

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.

相等的对象其hashcode值也相等。所以啊,重写了equals方法,则也得将hashcode()方法重写下。

 

JDK类中有一些类覆盖了oject类的equals()方法,比较规则为:如果两个对象的类型一致,并且内容一致,则返回true,这些类有:java.io.file,java.util.Date,java.lang.string,包装类(Integer,Double等)

String、Integer、Boolean、Double等这些类都重写了equals和hashCode方法,这两个方法是根据对象的内容来比较和计算hashCode的。所以只要对象的基本类型值相同,那么hashcode就一定相同。

 

2.再来看看 ==到底是什么

 ==是指引用是否相同

 

3.hashcode方法

Object类中的hashCode是返回对象在内存中地址转换成的一个int值(可以就当做地址看)。所以如果没有重写hashCode方法,任何对象的hashCode都是不相等的。通常在集合类的时候需要重写hashCode方法和equals方法, 因为如果需要给集合类(比如:HashSet)添加对象,那么在添加之前需要查看给集合里是否已经有了该对象,比较好的方式就是用hashCode。如果hashcode相同,对象就放不到集合类中了(hashset,hashmap,hashtable),通过哈希储存结构

 

 

equals()相等的两个对象,hashcode()一般是相等的,最好在重写equals()方法时,重写hashcode()方法; equals()不相等的两个对象,却并不能证明他们的hashcode()不相等。换句话说,equals()方法不相等的两个对 象,hashcode()有可能相等。 反过来:hashcode()不等,一定能推出equals()也不等;hashcode()相等,equals()可能相等,也可能不等。在 object类中,hashcode()方法是本地方法,返回的是对象的引用(地址值),而object类中的equals()方法比较的也是两个对象的 引用(地址值),如果equals()相等,说明两个对象地址值也相等,当然hashcode()也就相等了。

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值