Java List、Set去重实体对象类型的集合

1.//实体类中重写equals与hashCode方法
package test;

public class Student {

    private String name;

    private String age;

    private String sex;

//......省略getset方法
    @Override  
    public boolean equals(Object obj) {  
    Student s=(Student)obj;   
    return name.equals(s.name);   
    }   
    @Override
    public int hashCode() {  
    String in =  name;  
    return in.hashCode();  
    }
}
//2.将List转为Set,得到去重之后的集合
public class Main {
    public static void main(String[] args) {
        List list = new ArrayList();
        Student student = new Student();
        student.setName("lishiwei");
        student.setAge("22");
        student.setSex("1");
        list.add(student);
        student = new Student();
        student.setName("lishiwei");
        student.setAge("22");
        student.setSex("1");
        list.add(student);
        Set ts = new HashSet();  
        ts.addAll(list);  
        for (Student s : ts) {  
            System.out.println(student.getName());  
        } 
    }
}

你可能感兴趣的:(java)