在下面这个类中实现了Comparable接口,并重写了该接口中的compareTo()方法。
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo{
public static void main(String args[]){
TreeSet ts=new TreeSet();
ts.add(new Student("zhangsan01",22));
ts.add(new Student("zhangsan007",20));
ts.add(new Student("zhangsan09",19));
ts.add(new Student("zhangsan001",24));
ts.add(new Student("zhangsan08",23));
ts.add(new Student("zhangsan011",25)); //?
ts.add(new Student("zhangsan012",26)); //?
ts.add(new Student("zhangsan015",27)); //?? 疑问 zhangsan011、zhangsan012、zhangsan015这个三个对象存入时,这里自动择中比较是怎么择的呢? 运行结果我以看到了,不解是什么规律
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 name;
}
public int getAge(){
return 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 0;
return -1;
}
}
}
|