本帖最后由 李亚飞 于 2012-12-18 17:48 编辑
package collection;
import java.util.*;
public class TreeSetDemo2 {
/**
* 有个学生类:包含姓名和年龄。根据年龄从小到大排序(如果年龄相等 则按姓名排序)。
* 若姓名是字母的时候可以按字母排序,
* 若姓名是中文的时候该如何排序?
*/
public static void main(String[] args) {
meth_1();
}
public static void meth_1()
{
//传入比较器对象 new MyComparator()
TreeSet<Students> ts = new TreeSet<Students>(new MyComparator());
ts.add(new Students("lisi",21));
ts.add(new Students("zhangsan",20));
ts.add(new Students("along",21));
ts.add(new Students("admin",21));
ts.add(new Students("maer",23));
/* 若是中文该如何排序?
ts.add(new Students("李四",21));
ts.add(new Students("张三",20));
ts.add(new Students("阿龙",21));
ts.add(new Students("管理员",21));
ts.add(new Students("马二",23));
*/
//迭代器
Iterator<Students> it = ts.iterator();
while(it.hasNext())
{
Students s = it.next();
System.out.println("姓名:"+s.getName()+"\t年龄"+s.getAge());
}
}
}
class Students //学生类 :姓名 年龄
{
private String name ;
private int age ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Students(String name,int age) {
this.name = name;
this.age = age;
}
}
//比较器
class MyComparator implements Comparator<Students>
{
public int compare(Students s1,Students s2)
{
//根据年龄排序
int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if(num==0) //如果年龄相对 则按姓名排序
return num = s1.getName().compareTo(s2.getName()) ;
return num ;
}
}
|