java对象除了采用equals和hashCode判断对象是否相等外,开发人员也可以通过其他属性判断两个对象是否相等
以下案例采用TreeSet去掉重复对象
Teacher:
public class Teacher{ private String name; private Integer age; public Teacher(String name, Integer age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
TreeSetTest:
public class TreeSetTest{ public static void main(String[] args) { TreeSet<Teacher> set=new TreeSet<Teacher>(new Comparator<Teacher>() { @Override
//通过姓名和年龄判断对象是否相等 public int compare(Teacher o1, Teacher o2) { if(o1.getAge()>o2.getAge()){ return 1; }else if(o1.getAge()<o2.getAge()){ return -1; }else{ if(o1.getName().compareTo(o2.getName())>0){ return 1; }else if(o1.getName().compareTo(o2.getName())==0){ return 0; }else{ return -1; } } }; }); Teacher p1=new Teacher("小学",20); Teacher p2=new Teacher("初中",20); Teacher p3=new Teacher("高中",20); Teacher p4=new Teacher("初中",20); set.add(p1); set.add(p2); set.add(p3); set.add(p4); Iterator<Teacher> iterator = set.iterator(); while(iterator.hasNext()){ Teacher teacher = iterator.next(); System.out.print(teacher.getName()+" "); } } }
结果输出:
初中 小学 高中