面试------重写equals方法

22 篇文章 0 订阅

 

https://blog.csdn.net/lettyisme/article/details/80339637 我自己之前的总结

首先要知道equals方法得特性:自反性,,,,,,

自反性:对于任何非null的引用值x,x.equals(x)=true
对称性:对于任何非null的引用x,y,x.equals(y)=true,同样y.equals(y)=true
传递性:对于任何非null的引用x,y,z,x.equals(y)=true,x.equals(z)=true =>y.equals(z)=true
一致性:对于任何非null的引用x和y,只要equals的操作涉及的类信息没有改变,则x.equals(y)的结果一直不变;
对于任何为null的引用,null.equals(x)=false

重写equals方法的四个步骤:

(1)使用==操作符判断参数是否是这个对象的引用;//这个什么意思?
(2)使用instanceof操作符判断”参数是否是正确的类型“;
(3)把参数装换成正确的类型;
(4)对于参数中的各个域,判断其是否和对象中的域相匹配;

public boolean equals(Object obj) {//传入的参数是要比较的那个类吧
            if(this==obj){
                return true;
            }
            if(!(obj instanceof User)){
                return false;
            }
            final User user = (User) obj;
            if( this.userId == user.userId &&
                this.userName.equals(user.userName) &&
                this.password.equals(user.password) &&
                this.gender == user.gender
              ){
                return true;
            }
            return false;
            }
        public int hashCode(){
            int result = 0;
            result = this.userName.hashCode() + this.password.hashCode();
            result = this.gender.hashCode() + result;
            return result;
        }

 

可能会拓展考一下怎么计算hashcod

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值