TreeSet:可以对Set集合中的元素进行排序。其底层的数据结构是二叉树。
其保证元素唯一性的标志基于compareTo方法return 0;
TreeSet排序有两种方式:
1。让元素自身具有比较性,需要实现Comparable接口,覆盖compareTo方法。
2。当元素自身不具备比较性时,或者具备比较性不是开发所需要的时候,这时需要让集合自身具备可比较性。
在集合初始化时,就具备比较性。
下面代码分别实现了两种方法:
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new StringComparator() );
ts.add(new student("张三", 15));
ts.add(new student("李四", 12));
ts.add(new student("王五", 12));
ts.add(new student("张三", 16));
Iterator it = ts.iterator();
while (it.hasNext())
{
student s = (student) it.next();
System.out.println(s.getName() + " " + s.getAge());
}
}
}
class student implements Comparable
{
private String name;
private int age;
student(String name, int age)
{
this.name = name;
this.age = age;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
public int compareTo(Object obj)
{
if (!(obj instanceof student))
{
throw new RuntimeException("不是同一个对象");
}
student s = (student) obj;
if (this.age > s.age)
{
return 1;
}
if (this.age == s.age)
{
return s.getName().compareTo(this.name);
}
return -1;
}
}
class StringComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
student s1=(student)o1;
student s2=(student)o2;
int num=s1.getName().compareTo(s2.getName());
if (num==0)
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
student 类实现了方法一。StringComparator类实现方法二。
在实际开发中大多使用方法二。