对equals方法和 ==的理解

我们对两个对象进行equals比较,其实底层是根据  hashcode 返回的整数值决定的,hashcode的返回值 是根据

              由 Object 类定义的 hashCode 方法确实会针对不同的对象返回不同的整数。(这一般是通过将该对象的内部地址转换成一个整数来实现的,但是 JavaTM 编程语言不需要这种实现技巧。)

       String 类重写了hashcode方法,是根据字符串返回hashcode,这就意味着只要你输入的两个字符串的字母是相同的,那么它就会返回相同的hashcode,即使这是两个不同的对象。

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

hashcode和 equals方法是绑定在一起的,当我们修改hashcode方法时,我们也会同时修改equals方法。


在我们定义的数据分装类,如果我们不重写 hashcode和equals方法,两个不同的对象会返回false,但是当我们重写hashcode和equals方法,底层可以调用String的hashcode方法,这时只要我们对bean对象中分装的值相同就会返回true

    @Test
    public void testObject(){
        Student stu=new Student();
        stu.setId(0);
        stu.setName("nike");
        stu.setEmail("1233@qq.com");
        
        System.out.println(stu.hashCode());
        
        Student stu1=new Student();
        stu1.setId(0);
        stu1.setName("nike");
        stu1.setEmail("1233@qq.com");
        
        System.out.println(stu1.hashCode());

        boolean flag = stu1.equals(stu);
        
        System.out.println(flag);
        
        String str=new String();
        
    }

重写的hashcode和equals方法

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((email == null) ? 0 : email.hashCode());
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (email == null) {
            if (other.email != null)
                return false;
        } else if (!email.equals(other.email))
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }


等于一般对象保存的是对象的引用,及地址,因此只要是两个不同的对象,他们就不会相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值