本帖最后由 张豪杰 于 2013-2-25 11:45 编辑
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisi01",22));
ts.add(new Student("lisi02",20));
ts.add(new Student("lisi09",19));
ts.add(new Student("lisi08",19));
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 int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s =(Student)obj;
System.out.println(this.name+"....compareto...."+s.name);
if (this.age>s.age)
return 1;
if(this.age == s.age)
{
return this.name.compareTo(s.name);
}
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
------------------------------
lisi01....compareto....lisi01
lisi02....compareto....lisi01
lisi09....compareto....lisi01
lisi09....compareto....lisi02
lisi08....compareto....lisi02
lisi08....compareto....lisi09
lisi08....19
lisi09....19
lisi02....20
lisi01....22
怎么存入的第一个对象会自己和自己比较啊?
|
|