TreeSet集合第一次增加对象时会调用compsareTo方法??
import java.util.*;
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 stu = (Student)obj;
System.out.println(this.name+"::::"+stu.name); //为了观察compareTo是怎么运行的
if (this.age>stu.age)
{
return 1;
}
if (this.age == stu.age)
{
return this.name.compareTo(stu.name);
}
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class TreeSetTest
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lilei",9));
ts.add(new Student("hanmeimei",9));
ts.add(new Student("lilei001",9));
Iterator it = ts.iterator();
while (it.hasNext())
{
Student s = (Student)it.next();
System.out.println(s.getName()+"::"+s.getAge());
}
}
}
显示的是第一个对象先和自己比较了?