import java.util.*;
class Treeset
{
public static void main(String[] args)
{
TreeSet t = new TreeSet();
t.add(new student("a1",15));
t.add(new student("a2",15));
t.add(new student("a1",15));
t.add(new student("a3",16));
t.add(new student("a3",18));
for(Iterator it = t.iterator();it.hasNext();)
{
student tt = (student)it.next();//强制转成学生类型
sop(tt.getName()+","+tt.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class student implements Comparable//接口让学生具有比较性
{
private String name;
private int age;
student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof student))
throw new RuntimeException("不是学生");
student t = (student)obj;
if(this.age > t.age)
return 1;
if(this.age==t.age)
return this.name.compareTo
TreeSet --实现学生按年龄大小和姓名排序
最新推荐文章于 2024-08-14 22:53:03 发布
这篇博客探讨了如何利用TreeSet的compareTo方法,实现对学生对象按年龄大小和姓名进行排序的功能。
摘要由CSDN通过智能技术生成