/*
需求,往TreeSet集合中存储自定义对象学生。
想按照学生的年龄进行排序
注意:排序时,当主要条件相同时,一定要判断一下次要条件
*/
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 e)
{
if(!(e instanceof Student))
throw new RuntimeException("nononono");
Student stu=(Student)e;
if(this.age>stu.age)
return 1;
if(this.age==stu.age)
{
//return 0;返回0,对象相等
return this.name.compareTo(stu.name);//当年龄相同时,返回比较字符串的值,compareTo()按字典顺序比较两个字符串
}
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class Demo
{
public static void main(String[] args)
{
TreeSet it= new TreeSet();//定义一个临时容器
it.add(new Student("java4",34));//存入对象
it.add(new Student("java4",32));
it.add(new Student("java5",34));
it.add(new Student("java4",31));
it.add(new Student("java4",34));
//it=quChong(it);//传入集合,让contains()里的equals()作比较
Iterator al=it.iterator();
while(al.hasNext())
{//因为getName()和getAge()是在Student里的,Object()里没有,直接调用是会编译错误,所以要向下转型为Student类型
Student p=(Student)al.next();
sop(p.getName()+"----"+p.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
} |
|