TreeSet类与HashSet类十分类似。不过,数集是一个有序的集合。每次将一个元素添加到树中时,都被放置在正确的排序位置上。
TreeSet如何知道希望怎样排列的呢?在API文档中写道:The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. 使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。
1、树集假定插入的元素实现Comparable接口,即使用元素的自然顺序排序。
这里定义一个Person类,要插入到TreeSet中,且利用id排序。
import java.util.*;
public class Person implements Comparable<Person>
{
private String name;
private int id;
public Person(String n,int i)
{
name = n;
id = i;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public int compareTo(Person other)//利用id进行排序
{
return Integer.compare(id,other.id);
}
public String toString()
{
return "[Name="+name+",Id="+id+"]";
}
}
测试一下:
import java.util.*;
public class TreeSetT
{
public static void main(String []args)
{
SortedSet<Person> p = new TreeSet<>();
p.add(new Person("Coolbenn",24));
p.add(new Person("Jack",21));
p.add(new Person("Allen",25));
System.out.println(p);
}
}
得到结果为:
[[name=Jack,id = 21],[name=Coolbenn,id=24],[name=Allen,id=25]]
可见元素顺序是按id的值排列的。
2、构造带比较器的树,告诉树集使用不同的比较方法。
查阅API文档可见TreeSet的一个构造器:
public TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator. All elements inserted into the set must be mutually comparable by the specified comparator:
构造一个新的空 TreeSet,它根据指定比较器进行排序。插入到该 set 的所有元素都必须能够由指定比较器进行相互比较。
可见,应先实现一个Comparator对象。但接口不能实例化,所以通过实现Comparator接口的类来实现对象。
下面改为通过Person类的name作为排序规则:
import java.util.*;
public class TreeSetT
{
public static void main(String []args)
{
SortedSet<Person> p = new TreeSet<>();
p.add(new Person("Coolbenn",24));
p.add(new Person("Jack",21));
p.add(new Person("Allen",25));
//System.out.println(p);
class PersonComparator implements Comparator<Person>//构造比较器
{
public int compare(Person a,Person b)
{
String NameA = a.getName();
String NameB = b.getName();
return NameA.compareTo(NameB);
}
}
PersonComparator com = new PersonComparator();
SortedSet<Person> sortbyName = new TreeSet<>(com);//用比较器对象构造新的树集,排序规则为比较器compare()定义的规则。
sortbyName.addAll(p);
System.out.println(sortbyName);
}
}
看结果:
[[name=Allen,id=25],[name=Coolbenn,id=24],[name=Jack,id = 21]]
可见排序是按name字符串的字母顺序排序。
3、将比较器定义匿名内部类实例
这个比较器没有任何数据,只是比较方法的持有器,即类内部只定义了一个compare()方法。有时将这种对象称为函数对象(function object)。函数对象通常定义为匿名内部类实例。
SortedSet<Person> sortbyName = new TreeSet<>(new Comparator<Person>)
{
public int compare(Person a,Person b)
{
String NameA = a.getName();
String NameB = b.getName();
return NameA.compareTo(NameB);
}
}