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
3 个解决方案
#1
if(this.age==age){ //应该是if(this.age==s.age)
return this.name.compareTo(s.getName());
}
#2
if(this.age==age){ ////if(this.age==s.age),(由于颜色没设置成功,重新回复,没有其他意义)
return this.name.compareTo(s.getName());
#3
一个错误让我折腾了一两个小时啊 以后还的更小心了 谢谢啦~~
#1
if(this.age==age){ //应该是if(this.age==s.age)
return this.name.compareTo(s.getName());
}
#2
if(this.age==age){ ////if(this.age==s.age),(由于颜色没设置成功,重新回复,没有其他意义)
return this.name.compareTo(s.getName());
#3
一个错误让我折腾了一两个小时啊 以后还的更小心了 谢谢啦~~