import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("stu01",22));
ts.add(new Student("stui02",23));
ts.add(new Student("stu03",20));
ts.add(new Student("stu04",21));
ts.add(new Student("stu05",21));
ts.add(new Student("stu05",21));//被视为重复元素,不能写入
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+"..comparTo.."+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;
}
}
|