list集合去除重複物件
阿新 • • 發佈:2019-02-08
物件重複是指物件裡面的變數的值都相等,並不定是地址。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()); } } }