/*
* 程序头部注释开始
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:Map练习(二)
* 作 者:薛广晨
* 完成日期:2012 年 10 月 24 日
* 版 本号:x1.0
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述: 对学生对象的名字进行升序排序。
因为数据是以键值对形式存在的。
所以要使用可以排序的Map集合。TreeMap
* 程序输出:
* 程序头部的注释结束
*/
import java.util.*;
class StuNameComparator implements Comparator<Student>
{
public int compare(Student stu1, Student stu2)
{
int num = stu1.getName().compareTo(stu2.getName());
if(num == 0)
{
return new Integer(stu1.getAge()).compareTo(new Integer(stu2.getAge()));
}
return num;
}
}
class MapTest5
{
public static void main(String[] args)
{
TreeMap<Student, String> tm = new TreeMap<Student, String>(new StuNameComparator());
tm.put(new Student("blisi2",22),"shanghai");
tm.put(new Student("lisi1",21),"beijing");
//tm.put(new Student("lisi1",21),"tianjin");
tm.put(new Student("alisi4",24),"wuhan");
tm.put(new Student("lisi3",23),"nanjing");
Set<Map.Entry<Student, String>> entrySet = tm.entrySet();
for(Iterator<Map.Entry<Student, String>> it = entrySet.iterator(); it.hasNext(); )
{
Map.Entry<Student, String> me = it.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu + ":::" + addr);
}
}
}
Map练习(二)
最新推荐文章于 2022-05-18 10:33:31 发布