对象重复是指对象里面的变量的值都相等,并不定是地址。list集合存储的类型是基础类型还比较好办,直接把list集合转换成set集合就会自动去除。
当set集合存储的是对象类型时,需要在对象的实体类里面重写public boolean equals(Object obj) {}
和 public int hashCode() {}
两个方法。
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| 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(); } }
|
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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<Student> ts = new HashSet<Student>(); ts.addAll(stu); for (Student student : ts) { System.out.println(student.getId()+"-"+student.getName()); } } }
|