重写Java中包装类的方法

时间:2021-12-13 16:19:21

知识点
一、Object类
Object是所有类的父类。
Object中的方法有:
toString() 描述对象的信息,需要重写。System.out.println
在打印对象的时候会默认调用对象的toString()
equals() Object的equals方法用于对象的“相等”逻辑。

重写 toString()、equals():

 package day20190314;
public class User {
private int uid;
private String name;
private String phone;
public User(){ }
public User(int uid, String name, String phone) {
this.uid = uid;
this.name = name;
this.phone = phone;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString(){
return "编号:"+uid+",姓名:"+name+",电话:"+phone;
}
@Override
public boolean equals(Object obj){
if(obj==null)
return false;
//==比较的是内存地址
if(this==obj)
return true;
if(obj instanceof User){
User user=(User)obj;
return this.uid==user.uid;
}
return false;
}
//重写hashCode主要是给hashMap用
@Override
public int hashCode(){
return uid;
}
}
 package day20190314;
public class TestUser {
public static void main(String[] args) {
User user=new User(1,"root","123456");
User user1=new User(1,"root","123456");
System.out.println(user.equals(user1));
}
}

重写Java中包装类的方法