对象重复是指对象里面的变量的值都相等,并不定是地址。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;
}
// 省略get、set方法
......
@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();
}
}
测试:
public class Test {
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());
}
}
}