重写Java中包装类的方法

时间:2022-04-23 15:44:25

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

重写 toString()、equals():

 1 package day20190314;
 2 public class User {
 3         private int uid;
 4         private String name;
 5         private String phone;
 6         public User(){
 7             
 8         }
 9         public User(int uid, String name, String phone) {
10             this.uid = uid;
11             this.name = name;
12             this.phone = phone;
13         }
14         public int getUid() {
15             return uid;
16         }
17         public void setUid(int uid) {
18             this.uid = uid;
19         }
20         public String getName() {
21             return name;
22         }
23         public void setName(String name) {
24             this.name = name;
25         }
26         public String getPhone() {
27             return phone;
28         }
29         public void setPhone(String phone) {
30             this.phone = phone;
31         }
32         @Override
33         public String toString(){
34             return "编号:"+uid+",姓名:"+name+",电话:"+phone;
35         }
36         @Override
37         public boolean equals(Object obj){
38             if(obj==null)
39                 return false;
40             //==比较的是内存地址
41             if(this==obj)
42                 return true;
43             if(obj instanceof User){
44                 User user=(User)obj;
45                 return this.uid==user.uid;
46             }
47             return false;
48         }
49         //重写hashCode主要是给hashMap用
50         @Override
51         public int hashCode(){
52             return uid;
53         }
54 }
1 package day20190314;
2 public class TestUser {
3     public static void main(String[] args) {
4         User user=new User(1,"root","123456");
5         User user1=new User(1,"root","123456");
6         System.out.println(user.equals(user1));
7     }
8 }

 

重写Java中包装类的方法