import java.util.*;
class Cjd
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student("李雷",18,94));
ts.add(new Student("韩梅",19,97));
ts.add(new Student("露西",17,96));
ts.add(new Student("莉莉",17,94));
ts.add(new Student("汤姆",18,95));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println("\t"+"姓名:"+stu.getName()+" "+"年龄:"+stu.getAge()+" "+"成绩:"+stu.getResult());
}
}
}
class Student //implements Comparable
{
private String name;
private int age;
private int result;
Student(String name,int age,int result)
{
this.name=name;
this.age=age;
this.result=result;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}
public void setResult(int result)
{
this.result=result;
}
public int getResult()
{
return result;
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1 =(Student)o1;
Student s2 =(Student)o2;
int num = new Integer(s1.getResult()).compareTo(new Integer (s2.getResult()));
if(num==0)
return s1.getName().compareTo(s2.getName());这里如果我改成 return s1.compareTo(s2);就会编译失败,改为 return s1.getAge().compareTo(s2.getAge()); 也是失败。这是为什么啊? return num;
}
} |