我正在学习equals()和hashCode()方法,我认为这2个方法将帮助我们了解2个对象何时相等。但是下面的代码告诉我这是不正确的。
用户类别:
public class User {
private String name;
private int age;
private String passport;
public User(String name, int age, String passport) {
super();
this.name = name;
this.age = age;
this.passport = passport;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassport() {
return passport;
}
public void setPassport(String passport) {
this.passport = passport;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((passport == null) ? 0 : passport.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (passport == null) {
if (other.passport != null)
return false;
} else if (!passport.equals(other.passport))
return false;
return true;
}
}
主类:
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) {
User user1 = new User("mkyong", 35, "111222333");
User user2 = new User("mkyong", 35, "111222333");
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
System.out.println("user1 = " + user1);
System.out.println("user2 = " + user2);
System.out.println("user1 = " + user1.hashCode());
System.out.println("user2 = " + user2.hashCode());
System.out.println(user1.equals(user2));
System.out.println(user1 == user2);
User user = new User("mkyong", 35, "111222333");
System.out.println("Arraylist size = " + users.size());
System.out.println("Arraylist contains user = " + users.contains(user));
}
}
这是控制台中的输出:
user1 = arraylist.User@feea8b67
user2 = arraylist.User@feea8b67
user1 = -18183321
user2 = -18183321
true
false
Arraylist size = 2
Arraylist contains user = true
所以我看到用户具有相同的hashCode 18183321和相同的内存地址arraylist.User@feea8b67。而且我不明白为什么user1 == user2为假。