public static void main(String[] args) {
//List类型
List list=new ArrayList<>();
List list1=Arrays.asList(1L,2L,3L,4L,5L,6L);
List list2=Arrays.asList(4L,5L,6L);
HashSet h1 = new HashSet(list1);
HashSet h2 = new HashSet(list2);
h1.removeAll(h2);
list.addAll(h1);
System.out.println(list);//打印结果为:[1, 2, 3]
//List类型 同上
List s=new ArrayList<>();
List st=Arrays.asList("a","b","c","d");
List str=Arrays.asList("a","b","c");
HashSet hs1 = new HashSet(st);
HashSet hs2 = new HashSet(str);
hs1.removeAll(hs2);
s.addAll(hs1);
System.out.println(s);//打印结果为:[d]
}
1、创建一个User对象
public class User {
private Integer userId;
private String username;
private int sex;
private Integer age;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
super();
}
public User(Integer userId, String username, int sex, Integer age) {
super();
this.userId = userId;
this.username = username;
this.sex = sex;
this.age = age;
}
@Override
public String toString() {
return "User [userId=" + userId + ", username=" + username + ", sex=" + sex + ", age=" + age + "]";
}
}
2、同样的方法
public static void main(String[] args) {
List uList=new ArrayList();
uList.add(new User(1, "xxx", 1, 11));
uList.add(new User(2, "zzz", 1, 11));
uList.add(new User(3, "aaa", 1, 11));
uList.add(new User(4, "bbb", 1, 11));
List uList1=new ArrayList();
uList1.add(new User(1, "xxx", 1, 11));
HashSet h3 = new HashSet(uList);
HashSet h4 = new HashSet(uList1);
h3.removeAll(h4);
uList.removeAll(uList1);
uList.clear();
uList.addAll(h3);
//[User [userId=3, username=aaa, sex=1, age=11], User [userId=1, username=xxx, sex=1, age=11], User [userId=2, username=zzz, sex=1, age=11], User [userId=4, username=bbb, sex=1, age=11]]
System.out.println(uList);//结果并不是想要的
}
3、怎样才能做到去除list里的对象呢?
//重写hashCode和equals
@Override
public int hashCode() {
String result = username+userId;
return result.hashCode();
}
@Override
public boolean equals(Object obj) {
User u = (User)obj;
return this.getUsername().equals(u.getUsername()) && (this.getUserId().equals(u.getUserId()));
}
同上代码 重新运行 结果如下图所示:
微信扫描下方二维码(新开通的个人微信公众号) 更多优质资源及优质文章及时获取 请大家多多支持哦