去除ArrayList中重复自定义对象元素

时间:2023-01-24 19:32:42
 1 /*
2 * 自定义对象Person类
3 */
4 public class Person {
5 private String name;
6 private int age;
7
8 public Person(String name, int age) {
9 super();
10 this.name = name;
11 this.age = age;
12 }
13
14 public String getName() {
15 return name;
16 }
17
18 public void setName(String name) {
19 this.name = name;
20 }
21
22 public int getAge() {
23 return age;
24 }
25
26 public void setAge(int age) {
27 this.age = age;
28 }
29
30 @Override
31 public String toString() {
32 return "Person [name=" + name + ", age=" + age + "]";
33 }
34
35 @Override
36 public boolean equals(Object obj) {//重写equals方法
37 Person per = (Person) obj;
38 if (per.getName().equals(this.name) && per.getAge() == this.age) {
39 return true;
40 }
41 return false;
42 }
43
44 }

 

 //方式一:
1
import java.util.ArrayList; 2 import java.util.ListIterator;
3
4 import com.heima.bean.Person;
5
6 /*
7 * 需求:ArrayList去除集合中自定义对象元素的重复值(对象的成员变量值相同)
8 * 思路: 重写equals()方法
9 */
10 public class Demo2_ArrayList {
11 public static void main(String[] args) {
12 ArrayList<Person> list = new ArrayList<Person>();
13 list.add(new Person("张三", 23));
14 list.add(new Person("李四", 24));
15 list.add(new Person("王五", 25));
16 list.add(new Person("赵六", 26));
17 list.add(new Person("张三", 23));
18 list.add(new Person("李四", 24));
19 list.add(new Person("赵六", 26));
20 System.out.println(getSingle(list));
21 }
22
23 public static ArrayList<Person> getSingle(ArrayList<Person> list) {
24 ArrayList<Person> newArrayList = new ArrayList<Person>();
25 ListIterator<Person> iter = list.listIterator();
26 while (iter.hasNext()) {
27 Person per = (Person) iter.next();
28 if (!newArrayList.contains(per)) {//contains方法判断是否包含,底层依赖equals方法
29 newArrayList.add(per); //remove方法判断是否删除,底层依赖的也是equals方法
30 }
31 }
32
33 return newArrayList;
34
35 }
36
37 }

 

 1 //方式二:
2 public class ArrayList_Demo {
3 public static void main(String[] args) {
4 ArrayList<Person> list = new ArrayList<>();
5 list.add(new Person("张三", 23));
6 list.add(new Person("李四", 24));
7 list.add(new Person("王五", 25));
8 list.add(new Person("赵六", 26));
9 list.add(new Person("张三", 23));
10 list.add(new Person("李四", 24));
11 single(list);
12 System.out.println(list);
13 }
14
15 public static void single(List<Person> list) {
16 HashSet<Person> hash = new HashSet<>();
17 hash.addAll(list);
18 list.clear();
19 list.addAll(hash);
20 }
21
22 }