==与equals的区别

1.int,char,boolean之类的就是基本类型,我们只要使用==即可判断是否相等,无法使用equals

2.引用类型分为两类,第一类是重写过hashcode()和equals()方法的类,比如String,Integer,等,这些类使用==比较的是内存地址,即不同引用是否指向同一个对象,是,则true。equals比较则是直接比较对象的内容,不是判断不同引用是否指向同一个对象,只要对象里的各种参数完全一致,就为·true

3.第二类引用类型,就是没有重写过hashcode()和equals()方法的类,我们看Object类下的equals()方法

public boolean equals(Object obj) {
return (this == obj);
}
我们知道所有类都是Object类的子类,就是说如果子类不重写equals()方法,那么该类使用equals()方法就是使用Object下的equals,就是不同引用是否指向同一个对象,是,则true。如果我们希望实现普通类只比较对象的属性,可以对hashcode()和equals()进行重写,下面就是

class Student {
private String type;
private String name;
private int age;
Student(String type,String name,int age){
this.age=age;
this.type=type;
this.name=name;
}
@Override
public int hashCode() {
int B=31; // 31 131 1313 13131 131313 etc…
int hash=0;
hash=hashB+age;
hash=hash
B+type.toUpperCase().hashCode();
hash=hash*B+name.toUpperCase().hashCode();
return hash;
}

@Override
public boolean equals(Object obj) {
    if(this==obj){
        return true;
    }
    if(obj==null){
        return false;
    }
    Student student=(Student) obj;
    return student.hashCode()==this.hashCode();
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值