/*按照年龄进行排序的*/
import java.util.*;
public class TreeSetDemo
{
public static void main(String args[]){
TreeSet t = new TreeSet();
t.add(new Person("zhangsan",20));
t.add(new Person("Lisi",23));
t.add(new Person("wangwu",45));
t.add(new Person("haha",63));
Iterator li = t.iterator();
while(li.hasNext()){
Object obj = li.next();
Person pp = (Person)obj;
sop(pp.getName() + "...." + pp.getAge());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
class Person implements Comparable
{
private String name;
private int age;
public Person(String name,int age){
this.setName(name);
this.setAge(age);
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public int compareTo(Object obj){
if(!(obj instanceof Person))
throw new RuntimeException("不是Person类");
Person p = (Person)obj;
if(this.age>p.age){
return 1;
}
if(this.age==p.age){
return this.name.compareTo(p.name);
}
return -1;
}
}
希望对楼主有所帮助 |