TreeSet,当你执行add()方法的时候,集合会自动排序,所以是一种有序的集合。
使用TreeSet有两种方法:
一、元素实现Comparable接口,然后直接通过add方法添加元素即可。
二、创建一个Comparator,并在构造TreeSet的时候传入,如下:
//我这里Person为待添加元素
Set<Person> persons = new TreeSet<Person>(new PersonComparator());
现在需求很简单,根据Person的优先级字段(Priority)进行排序,Person类代码如下:
public class Person implements Comparable<SortPerson> {
private String personName;
private Integer priority;
public SortPerson() {
}
public SortPerson(String personName, Integer priority) {
this.personName = personName;
this.priority = priority;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
@Override
public int compareTo(SortPerson o) {
return priority.compareTo(o.getPriority());
}
}
测试代码如下:
@Test
public void sortPerson() {
Set<SortPerson> persons = new TreeSet<SortPerson>();
persons.add(new SortPerson("001", 1));
persons.add(new SortPerson("002", 1));
persons.add(new SortPerson("003", 1));
assertEquals(3, persons.size()); // ①
}
测试并没有通过,在行①,这里实际集合size为1,出了什么问题呢?
soga,原来TreeSet的add方法会先调用Person的compareTo方法判断元素是否重复,因为Priority全部为1,所以TreeSet认为后两个Person是重复的,这样的结果显然不是我们想要的,重新实现compareTo方法如下:
@Override
public int compareTo(SortPerson o) {
int compare1 = priority.compareTo(o.getPriority());
return compare1 == 0 ? this.personName.compareTo(o.personName) : compare1;
}
再次运行测试,OK了。
这个代码证明了TreeSet集合添加元素时的特点,和比较的特性,判断相等的依据。