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对象按年龄排序
最新推荐文章于 2023-11-17 11:12:22 发布
本文介绍了一个使用Java TreeSet实现的示例程序,该程序通过自定义的Person类演示了如何根据年龄对对象进行排序。TreeSet确保了元素的唯一性和有序性,而Person类实现了Comparable接口来定义比较规则。
883

被折叠的 条评论
为什么被折叠?



