import java.util.*;
class Set
{
public static void main(String[] args)
{
TreeSet hs=new TreeSet();
hs.add(new Person("torylee01",77));
hs.add(new Person("torylee02",44));
hs.add(new Person("torylee01",55));
hs.add(new Person("torylee01",66));
Iterator it=hs.iterator();
while(it.hasNext())
{
Person p=(Person)it.next();
System.out.println(p.getName()+".........."+p.getAge());
}
}
}
class Person implements Comparable
{
private String name;
private int age;
Person(String name, int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Person))
throw new RuntimeException("sorry, error");
Person p=(Person)obj;
if(this.age>p.age)
return 1;
if(this.age==p.age)
return 0;
return -1;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
}
对Person对象按年龄排序
最新推荐文章于 2022-07-17 11:04:39 发布