TreeSet:可以对Set集合中元素排序。
TreeSet 底层数据结构是 二叉树
保证元素唯一性依据是 compareTo 方法的 返回值。
TreeSet 排序方法:
1. 元素自身具有比较性,自定义元素 覆盖 compareTo 方法,这种方式称为元素自然排序和默认顺序。
2. 元素自身不具备比较性,或具备比较性不是所需要的,需要让集合自身在初始化时具备比较性
当两种方式都存在,以有比较强的排序方式为主。
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyComparator());
ts.add(new Person("lisa011",23));
ts.add(new Person("sa002",23));
ts.add(new Person("sa002",24));
ts.add(new Person("dsa002",24));
ts.add(new Person("dsa003432",12));
Iterator it = ts.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();
System.out.println(p.getName()+"::"+p.getAge());
}
}
}
//按照用户的年龄排序,年龄相同按照姓名排序
class Person implements Comparable{
private String name;
private int age ;
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
Person(String name,int age)
{
this.name = name;
this.age = age ;
}
public int compareTo(Object o1)
{
if(!(o1 instanceof Person))
throw new RuntimeException("不是学生!");
Person p =(Person)o1;
if(this.age > p.age)
return 1;
if(this.age == p.age)
return this.name.compareTo(p.name);
return -1;
}
}
//按照用户的姓名长度排序
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
if(!((o1 instanceof Person)&&(o2 instanceof Person)))
throw new RuntimeException("有对象不是学生!");
Person p1 = (Person)o1;
Person p2 = (Person)o2;
return new Integer(p1.getName().length()).compareTo(new Integer(p2.getName().length()));
}
}