import java.util.*;
class Person implements Comparable
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public int compareTo(Object obj)
{
if (!(obj instanceof Person))
{
throw new RuntimeException("吊爆了!");
}
Person p=(Person)obj;
if (this.age>p.age)
{
return 1;
}
if (this.age==p.age)
{
return this.name.compareTo(p.name);
}
return -1;
}
}
class TreeSetTest
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new Mycompare());
t.add(new Person("xxc1",15));
t.add(new Person("xxc2",20));
t.add(new Person("xxc3",17));
t.add(new Person("xxc4",16));
t.add(new Person("xxc4",10));
Iterator t1=t.iterator();
while (t1.hasNext())
{
Person p=(Person)t1.next();
System.out.println(p.getName()+"======"+p.getAge());
}
}
}
class Mycompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Person p=(Person)o1;
Person p1=(Person)o2;
int num=p.getName().compareTo(p1.getName());
if (num==0)
{
return new Integer (p.getAge()).compareTo(new Integer(p1.getAge()));
}
return num;
/*if (num>0)
{
return 1;
}
if (num==0)
{
if (p.getAge()>p1.getAge())
{
return 1;
}
if (p.getAge()==p1.getAge())
{
return 0;
}
if (p.getAge()<p1.getAge())
{
return -1;
}
}
if (num<0)
{
return -1;
}
return num;*/
}
}
TreeSet的第一种排序方式是实现Comparable接口覆写compareTo方法,此排序是自然顺序排序。
TreeSet的第二种排序方式是实现Comparator接口覆写compare方法,此排序是在集合一初始化就拥有的,所以要讲此接口的实例对象传入到TreeSet的构造函数中!!!