实体类User
import java.util.Objects;
public class User {
private String userName;
private String userCode;
public User() {
}
public User(String userName, String userCode) {
this.userName = userName;
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
@Override
public boolean equals(Object obj){
if(obj instanceof User){
User user = (User)obj;
return this.userName.equals(user.getUserName()) && this.userCode.equals(user.getUserCode());
}
return super.equals(obj);
}
@Override
public int hashCode(){
return Objects.hash(this.userName, this.userCode);
}
}
测试类
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws Exception {
List<User> userList = new ArrayList<User>();
User u1 = new User("name1","code1");
User u2 = new User("name2","code2");
userList.add(u1);
userList.add(u2);
//name、code都相同返回true
User u3 = new User("name2","code2");
System.out.println(userList.contains(u3));
//返回false
User u4 = new User("name1","code2");
System.out.println(userList.contains(u4));
}
}