TreeSet去重
首先TreeSet可以实现排序
@org.junit.Test
public void testHashSet() {
Person person = new Person("1",1,1);
Person person1 = new Person("1",1,2);
Person person2 = new Person("2",1,2);
TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if(o1.getName().equals(o2.getName())){
return 0;
}
if(o1.getAge() > o2.getAge()){
return 1;
}else {
return -1;
}
}
});
}
/**
public Person(String name, int age,int money) {
this.name = name;
this.age = age;
this.money = money;
}
这是Person类的构造器
*/
在treeSet创建的时候,重写了以下代码
1.
TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return 0;//Person o1留下,o2添加失败
return -1;//倒序存储
return 1;//升序存储
}
});
这个方法中,return 0;是无法添加的
2.当然也可以在Person类中实现comparable接口,重写接口中的compareTo方法,具体实现和上面的方法没有太大区别
HashSet
HashSet是通过HashMap实现的,
hashCode()和equals()是HashMap用的, 因为无需排序所以只需要关注定位和唯一性即可
修改Person类中的hashCode()和equals()方法,两个都要修改