The list collection removes the implementation of duplicate objects

  • 2020-05-30 20:05:45
  • OfStack

Object duplication means that all variables in an object have the same value, not necessarily the address. The list collection storage type is the base type, which is easy to handle. If you directly convert the list collection to the set collection, it will be automatically removed.

When an set collection stores an object type, you need to override public boolean equals(Object obj) {} and public int hashCode() {} methods in the object's entity class.

Entity class


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();
}
}

The test class


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 Collections hold objects that reference different addresses 
 Set<Student> ts = new HashSet<Student>();
 ts.addAll(stu);
 
 for (Student student : ts) {
  System.out.println(student.getId()+"-"+student.getName());
 }
 }
}


Related articles: