list集合去除重复对象 - html/css语言栏目:html.cs

  对象重复是指对象里面的变量的值都相等,并不定是地址。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());  
        }  
    }  
}  

 

   
返回顶部
跳到底部

Copyright 2011-2024 南京追名网络科技有限公司 苏ICP备2023031119号-6 乌徒帮 All Rights Reserved Powered by Z-BlogPHP Theme By open开发

请先 登录 再评论,若不是会员请先 注册