日期:2014-05-20  浏览次数:20683 次

往TreeSet集合中存储自定义对象学生,想按照学生的年龄进行升序排序,为什么结果是这样滴捏?
import java.util.*;

public class TreeSetDemo {
public static void main(String[] args) 

{
TreeSet ts=new TreeSet();

ts.add(new Student("lisi01",20));
ts.add(new Student("lisi07",25));
ts.add(new Student("lisi07",20));
ts.add(new Student("lisi09",19));
ts.add(new Student("lisi08",16));

Iterator it=ts.iterator();
while(it.hasNext()){
Student stu=(Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}

}

package student.treeset;

public class Student implements Comparable{  
private String name;
private int age;

public Student(String name,int age){
this.name=name;
this.age=age;
}

public String getName(){
return name;
}
public int getAge(){
return 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==age){
return this.name.compareTo(s.getName());
}
return -1;

}
}
结果:
lisi01...20
lisi07...25
lisi08...16
lisi09...19





------解决方案--------------------
Java code

if(this.age==age){       //应该是if(this.age==[color=#FF6600]s.age[/color])
return this.name.compareTo(s.getName()); 
}