equals  是在Object方法中定义的,直接用==来实现的,如果想比较具体的值,需要重写

重写equals方法

1 User.java
 2 
 3 public class User {
 4 
 5     String name;
 6 
 7     public String getName() {
 8         return name;
 9     }
10 
11     public void setName(String name) {
12         this.name = name;
13     }
14     User(String name){
15         this.name= name;
16     }
17 
18     @Override
19     public String toString() {
20         return "User [name=" + name + "]";
21     }
22 
23     @Override
24     public int hashCode() {
25         final int prime = 31;
26         int result = 1;
27         result = prime * result + ((name == null) ? 0 : name.hashCode());
28         return result;
29     }
30 
31     @Override
32     public boolean equals(Object obj) {
33         if (this == obj)
34             return true;
35         if (obj == null)
36             return false;
37         if (getClass() != obj.getClass())
38             return false;
39         User other = (User) obj;
40         if (name == null) {
41             if (other.name != null)
42                 return false;
43         } else if (!name.equals(other.name))
44             return false;
45         return true;
46     }
47 
48 }

测试重写好的方法

1 Test.java
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         
 7         
 8         User uz = new User("张三");
 9         User ul = new User("张三");
10         
11         
12         System.out.println(uz.equals(ul));
13     }
14 }