java 中equals方法研究

   以前学java时没有深入,之后又主要从事web开发,对于java深层次基础的东西就用得少了,今天看到一个简单的程序居然做错了,哈哈,如下:

class Value {
    int i;
}

public class EqualsMethod2 {
    public static void main(String[] args) {
        Value v1 = new Value();
        Value v2 = new Value();
        v1.i = v2.i = 100;
        System.out.println(v1.equals(v2));
    }
}
原本都是以为equals是比较内容,==是比较地址的,好像对这道题不适用哈,查了一下API,终于知道怎么回事了,

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

也就是说object类中的equals是用来比较是否是同一个对象,也就是内存地址,只有重写了equals方法才能说是比较内容的,java API中好多类都重写了equals方法,这也就是为什么我看到这道题时有疑惑的原因,就本题而言,如果把v1和v2声明成String类等java封装的类,那么结果肯定是true了。这里需要指出的是equals只能用于对象,而不能用于基本类型,这是thinking in java中的一段描述,如下

What if you want to compare the actual contents of an object for equivalence? You must use the special method equals() that exists for all objects(not primitive ,which work fine with ==and !=)


下面的这段API说明,告诉我们重写equals方法的时候也要重写hashCode方法,原因是要维护hashCode常规协定,这个协定就是说,相等的对象必须要有相等的哈希码

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又是什么方法呢,如下

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

这里就涉及到哈希表了,学过数据结构的就比较清楚,如下

This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

这里说的就比较清楚了,至于进一步的联系,我还在研究之中,之后会更新的。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值