list集合去除重复对象的实现
作者:jingxian 时间:2022-10-16 23:02:42
对象重复是指对象里面的变量的值都相等,并不定是地址。list集合存储的类型是基础类型还比较好办,直接把list集合转换成set集合就会自动去除。
当set集合存储的是对象类型时,需要在对象的实体类里面重写public boolean equals(Object obj) {} 和 public int hashCode() {} 两个方法。
实体类
public class Student {
public String id;
public String name;
public Student() {
}
public Student(String id,String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
Student s=(Student)obj;
return id.equals(s.id) && name.equals(s.name);
}
@Override
public int hashCode() {
String in = id + name;
return in.hashCode();
}
}
测试类
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class QuSame {
public static void main(String[] args) {
List<Student> stu = new ArrayList<Student>();
stu.add(new Student("1","yi"));
stu.add(new Student("3","san"));
stu.add(new Student("3","san"));
stu.add(new Student("2","er"));
stu.add(new Student("2","er"));
//set集合保存的是引用不同地址的对象
Set<Student> ts = new HashSet<Student>();
ts.addAll(stu);
for (Student student : ts) {
System.out.println(student.getId()+"-"+student.getName());
}
}
}
标签:list,集合,重复,对象
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android使用JobScheduler定期推送本地通知实例代码
2023-07-26 22:43:28
如何优雅的处理Spring Boot异常信息详解
2023-11-29 09:50:02
![](https://img.aspxhome.com/file/2023/6/60536_0s.jpg)
在Spring中编写事务的介绍
2021-12-15 10:33:18
Java实现多个wav文件合成一个的方法示例
2021-10-08 08:14:25
java实现简单石头剪刀布游戏
2023-07-20 05:31:37
![](https://img.aspxhome.com/file/2023/8/57628_0s.jpg)
C#超市收银系统设计
2023-06-21 00:00:09
![](https://img.aspxhome.com/file/2023/9/66579_0s.png)
利用Java8 Optional类优雅如何地解决空指针问题
2023-07-30 04:58:13
Java实现双保险线程的示例代码
2023-09-21 07:59:46
简单了解springboot的jar包部署步骤
2021-07-02 14:22:48
java中的文件操作总结(干货)
2023-11-08 22:24:29
idea 有时提示找不到类或者符号的解决
2023-11-29 04:10:43
![](https://img.aspxhome.com/file/2023/9/60779_0s.jpg)
Java程序图形用户界面设计之按钮与布局
2023-07-18 07:03:21
![](https://img.aspxhome.com/file/2023/2/61572_0s.png)
实现java简单的线程池
2023-08-09 06:05:15
![](https://img.aspxhome.com/file/2023/5/58065_0s.png)
Java如何在沙箱环境中测试支付宝支付接口
2023-11-02 14:55:15
![](https://img.aspxhome.com/file/2023/5/58745_0s.png)
IDEA中sout快捷键无效问题的解决方法
2023-11-28 21:27:02
![](https://img.aspxhome.com/file/2023/7/60817_0s.png)
基于Java实现缓存Cache的深入分析
2023-08-15 20:53:59
一文详解Reactor模型与实现示例
2023-11-13 12:22:09
![](https://img.aspxhome.com/file/2023/6/59396_0s.png)
Maven学习----Maven安装与环境变量配置教程
2021-12-04 08:20:25
![](https://img.aspxhome.com/file/2023/8/60678_0s.png)
SpringBoot 开发提速神器 Lombok+MybatisPlus+SwaggerUI
2022-07-08 07:40:23
![](https://img.aspxhome.com/file/2023/6/61516_0s.jpg)
Java 通过反射给实体类赋值操作
2023-11-26 10:11:41