需求: 往TreeSet 集合中存储自定义对象学生要求学生按照年龄排序。
注意: 在主要条件相同的情况下,要判断次要条件。
import java.util.TreeSet;
import java.util.Iterator;
class Student implements Comparable //定义学生类实现Comparable接口
{
private String name;
private int age;
Student(String name,int age)
{
setName(name);
setAge(age);
}
public int compareTo(Object obj) //重写compareTo()方法
{
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));
return -1;
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
public class TreeSetDemo
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("xiaoming1",14));
ts.add(new Student("xiaoming2",12));
ts.add(new Student("xiaoming3",15));
ts.add(new Student("xiaoming4",11));
ts.add(new Student("xiaoming0",11));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu =(Student)it.next();
sop(stu.getName()+"---"+stu.getAge());
}
}
}
|
|