public int compareTo(Object O){
if(O instanceof person1){
person1 person = (person1) O;
int age = this.age-person1.age;
if(age == 0)
return this.name.compareTo(O.name);
return age;
}else{
throw new ClassCastException("不能转为PERSON类型");
}
}
如果以上代码还是不行的话,那就是你的hashCode的问题了。
我给你写了一个例子,你自己看下吧。import java.util.*;
public class TreeSetDemo{
public static void main(String[] args){
TreeSet set = new TreeSet();
set.add(new Person("BB",19));
set.add(new Person("AA",12));
set.add(new Person("EE",14));
set.add(new Person("CC",14));
set.add(new Person("DD",15));
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Person implements Comparable{
private String name;
private int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public int compareTo(Person p){
int paixu = this.age - p.age;
if(paixu == 0)
return this.name.compareTo(p.name);
else
return paixu;
}
public String toString(){
return this.name+"="+this.age;
}
}