JavaTreeSet实现学生按年龄大小和姓名排序的方法示例-创新互联
本文实例讲述了Java TreeSet实现学生按年龄大小和姓名排序的方法。分享给大家供大家参考,具体如下:

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(t.name);//如果年龄相同,在比较姓名排序
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
名称栏目:JavaTreeSet实现学生按年龄大小和姓名排序的方法示例-创新互联
网页地址:http://www.jxjierui.cn/article/cojgdh.html


咨询
建站咨询
