import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisa001", 32));
// ts.add(new Student("lisa003", 234));
// ts.add(new Student("lisa006", 33));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"...."+stu.getAge());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
Student(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public int compareTo(Object obj)
{
if (!(obj instanceof Student))
throw new RuntimeException("不是学生类型");
Student stu = (Student)obj;
System.out.println(this.name+"...compareto..."+stu.name);
if (this.age > stu.age)
return 1;
if (this.age == stu.age)
return this.name.compareTo(stu.name);
return -1;
}
}
结果:
lisa001...compareto...lisa001
lisa001....32