Set去重原理流程:
Set下的HashSet集合通过集合元素的hashCode()方法和equals()方法来进行去重复,如果两个元素的hashCode相等,然后再去调用equals方法,如果也相等,那么就认为这两个元素相等,第二个元素就不会添加到集合中,从而保证了元素的去重复;
重写User实体的hashCode、equal方法,如下:
-
package com.betawoo.core.entity;
-
-
-
import java.util.Date;
-
import java.util.List;
-
import java.util.Map;
-
-
/**
-
* Created by HGG 16/10/11.
-
*/
-
public class User {
-
-
private String userId;
-
private String userName;
-
private String email;
-
-
public String getUserId() {
-
return userId;
-
}
-
-
public void setUserId(String userId) {
-
this.userId = userId;
-
}
-
-
public String getUserName() {
-
return userName;
-
}
-
-
public void setUserName(String userName) {
-
this.userName = userName;
-
}
-
-
public String getEmail() {
-
return email;
-
}
-
-
public void setEmail(String email) {
-
this.email = email;
-
}
-
-
/**
-
* set<User></>去重,重新如下两个方法hashCode、equals
-
*/
-
-
public int hashCode(){
-
return userId.hashCode();
-
}
-
-
-
public boolean equals(Object obj){
-
if(obj instanceof User){
-
User user=(User)obj;
-
return userId.equals(user.userId);
-
}
-
return super.equals(obj);
-
}
-
-
}
感谢