用TreeSet可以装入Person类对象,并设定的compareTo方法 控制输出顺序
import java.util.*;
class StudentTest
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add(new Student("stu03",23,98));
ts.add(new Student("stu02",20,94));
ts.add(new Student("stu01",28,100));
ts.add(new Student("stu06",27,87));
ts.add(new Student("stu07",23,92));
print(ts);
}
public static void print(TreeSet ts)//遍历打印
{
for (Iterator it=ts.iterator();it.hasNext() ; )
{
Object obj=it.next();
Student stu=(Student)obj;
System.out.println(stu.getName()+"::"+stu.getAge()+"::"+stu.getScore());
}
}
}
class Student implements Comparable//类Student 私有name,age,score成员变量,实现set,get方法
{
private String name;
private int age;
private int score;
public Student(String name,int age,int score)//初始化
{
this.name=name;
this.age=age;
this.score=score;
}
public String getName()//获取名字
{
return(name);
}
public int getAge()//获取年龄
{
return(age);
}
public int getScore()//获取分数
{
return(score);
}
public void setName(String name)//重新设定名字
{
this.name=name;
}
public void setAge(int age)//重新设定年龄
{
this.age=age;
}
public void setScore(int score)//重新设定分数
{
this.score=score;
}
public int compareTo(Object obj)
{
Student stu=(Student)obj;
int num1=stu.score-this.score;
int num2=this.name.compareTo(stu.name);
int num3=this.age-stu.age;
if(num1==0)
{
if (num2==0)
{
return num3;
}
return num2;
}
return num1;
}
}
|