- TreeSet 的去重是由所add对象声明的compareTo 决定的,而HashSet 会先去比较对象的hashcode 方法返回值,如果相同,再去比较对象的equals方法。因此一般可以通过改写对象的hashcode 和equals方法来修改对象的判重规则。
package baidu.Javabase.comparator;
/**
* Created by liuchaoqun01 on 18/6/9.
*/
public class Person implements Comparable {
private String name;
private Integer age;
private String mind;
public Person(String name, Integer age, String mind) {
this.name = name;
this.age = age;
this.mind = mind;
}
/**
* 比较方法在类中声明,一般是传入一个类和当前类比较
* @param o
* @return
*/
public int compareTo(Object o) {
Person person = (Person) o;
int ret = this.name.compareTo(person.getName());
if (ret == 0) {
ret = Integer.compare(this.age, person.getAge());
}
if (ret == 0) {
return this.getMind().compareTo(person.getMind());
}
return ret;
}
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;
}
public String getMind() {
return mind;
}
public void setMind(String mind) {
this.mind = mind;
}
}
package baidu.Javabase.comparator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* Created by liuchaoqun01 on 18/6/9.
*/
public class TestComparable {
//生成待排序数组
private static List<Person> generatePersonList() {
List<Person> retList = new ArrayList<>(16);
retList.addAll(Arrays.asList(new Person("erMaZi", 19, "good"), new Person("liSi", 17, "bad")
, new Person("wangWu", 18, "middle")
, new Person("wangWu", 18, "middle")));
return retList;
}
public static void print(String message,List<Person> personList){
System.out.println(message+":");
for(Person p:personList){
System.out.println(p);
}
System.out.println();
}
public static void print(String message,SortedSet<Person> sortedSet){
System.out.println(message+":");
for(Person p:sortedSet){
System.out.println(p);
}
System.out.println();
}
public static void main(String[] args) {
//取数据
List<Person> personList = generatePersonList();
//排序一: 正常 这个并未指定比较器,是用的类本身的比较器
Collections.sort(personList);
print("Collections.sort(list)",personList);
//排序二:发现正常了
PersonComparator pc = new PersonComparator();
PersonComparator2 pc2 = new PersonComparator2();
Collections.sort(personList,pc.thenComparing(pc2)); // 这里是先按照pc排序,再按照pc2 排序
print("thenComparing",personList);
//排序三:正常
SortedSet<Person> ts = new TreeSet<>(personList);
print("TreeSet",ts);
//排序四:发现某个Person实例被吃掉了,因为TreeSet认为CompareTo为0,则两个Person实例相同
SortedSet<Person> ts2 = new TreeSet<>(new PersonComparator());
ts2.addAll(personList);
print("TreeSet(Comparator)",ts2);
List<Integer> list = Arrays.asList(1, 2, 1,3,5,3);
SortedSet<Integer> it = new TreeSet<>(list);
System.out.println(it);
}
}
参考:https://blog.csdn.net/yxb_yingu/article/details/52194988
网友评论