话不多说,先上代码
public static void main(String[] args) {
//List<long>类型
List<Long> list=new ArrayList<>();
List<Long> list1=Arrays.asList(1L,2L,3L,4L,5L,6L);
List<Long> 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<String>类型 同上
List<String> s=new ArrayList<>();
List<String> st=Arrays.asList("a","b","c","d");
List<String> 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]
}
延伸:如果要去除List<Object>呢?是否还可以?
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<User> uList=new ArrayList<User>();
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<User> uList1=new ArrayList<User>();
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方法
//重写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()));
}
同上代码 重新运行 结果如下图所示:
微信扫描下方二维码(新开通的个人微信公众号) 更多优质资源及优质文章及时获取 请大家多多支持哦