本帖最后由 王少岩 于 2012-8-15 09:48 编辑
import java.util.*;
class TreeDemo
{
public static void main(String[] args)
{
TreeSet<Student> tr = new TreeSet<Student>();
tr.add(new Student("lisi01",11));
tr.add(new Student("lisi02",12));
tr.add(new Student("lisi03",13));
tr.add(new Student("lisi04",14));
tr.add(new Student("lisi05",15));
tr.add(new Student("lisi06",16));
for(Student stu : tr)
{
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+"..."+s.name);
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
};
结果:
lisi02...lisi01
lisi03...lisi01
lisi03...lisi02
lisi04...lisi02
lisi04...lisi03
lisi05...lisi02
lisi05...lisi03
lisi05...lisi04
lisi06...lisi02
lisi06...lisi04
lisi06...lisi05
lisi01....11
lisi02....12
lisi03....13
lisi04....14
lisi05....15
lisi06....16
treeSet集合在添加元素的时候,新增的元素跟已存在的元素比较的先后顺序是如何的?也就是说先跟谁比较后跟谁比较,写了个treeSet的demo,但是看得运行结果,有点疑惑
|