软件编程
位置:首页>> 软件编程>> java编程>> Java TreeSet实现学生按年龄大小和姓名排序的方法示例

Java TreeSet实现学生按年龄大小和姓名排序的方法示例

作者:chaoyu168  发布时间:2023-01-09 15:25:18 

标签:Java,TreeSet,排序

本文实例讲述了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程序设计有所帮助。

来源:http://blog.csdn.net/chaoyu168/article/details/49335977

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com