本文实例讲述了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;
}
}
compareto
int compareto(t o)
比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。
实现类必须确保对于所有的 x 和 y 都存在 sgn(x.compareto(y)) == -sgn(y.compareto(x)) 的关系。(这意味着如果 y.compareto(x) 抛出一个异常,则 x.compareto(y) 也要抛出一个异常。)
实现类还必须确保关系是可传递的:(x.compareto(y)>0 && y.compareto(z)>0) 意味着 x.compareto(z)>0。
最后,实现者必须确保 x.compareto(y)==0 意味着对于所有的 z,都存在 sgn(x.compareto(z)) == sgn(y.compareto(z))。 强烈推荐 (x.compareto(y)==0) == (x.equals(y)) 这种做法,但并不是 严格要求这样做。一般来说,任何实现 comparable 接口和违背此条件的类都应该清楚地指出这一事实。推荐如此阐述:“注意:此类具有与 equals 不一致的自然排序。”
在前面的描述中,符号 sgn(expression) 指定 signum 数学函数,该函数根据 expression 的值是负数、零还是正数,分别返回 -1、0 或 1 中的一个值。
参数:
o - 要比较的对象。
返回:
负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。
抛出:
classcastexception - 如果指定对象的类型不允许它与此对象进行比较。
以上就是java中使用treeset如何实现按年龄大小和姓名排序的示例的详细内容。