package myclass;
import java.util.;
/
往TreeSet集合中存储自定义对象学生
向按照学生的年龄进行排序。
需要实现Compareable 接口。
当主要条件相同时,就需要比较次要条件
*/
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;
if(this.age > s.age)
return 1;
if(this.age == s.age)
{
return this.name.compareTo(s.name);
}
else
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("zhangsan",30));
ts.add(new Student("lisi",25));
ts.add(new Student("wuliu",23));
ts.add(new Student("wuliu0",23));
ts.add(new Student("zhansan",21));
Iterator it = ts.iterator();
while(it.hasNext())
{ Student stu = (Student)it.next();
System.out.println(stu.getName() + " ::" + stu.getAge());
}
}
}