A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

  1. import java.util.*;

  2. public class MapDemo1 {

  3.         public static void main(String[] args)
  4.         {
  5.                 Map<Student, String> stuMap = new TreeMap<Student, String>(new Comp());
  6.                 stuMap.put(new Student("胡平燕1", 21),"湖南1");
  7.                 stuMap.put(new Student("胡平燕2", 23),"湖南2");
  8.                 stuMap.put(new Student("胡平燕3", 50),"湖南4");
  9.                 stuMap.put(new Student("胡平燕3", 29),"湖南4");
  10.                 stuMap.put(new Student("胡平燕3", 29),"湖南3");
  11.                
  12.                
  13.                 Set<Student> keySet = stuMap.keySet();
  14.                 for(Iterator<Student> it = keySet.iterator(); it.hasNext();)
  15.                 {
  16.                         Student key = it.next();
  17.                         String name= stuMap.get(key);
  18.                         System.out.println(key.getName()+" "+key.getAge()+" "+name);                       
  19.                 }
  20.         }

  21. }

  22. class Comp implements Comparator<Student>
  23. {
  24.         @Override
  25.         public int compare(Student o1, Student o2)
  26.         {
  27.                 int num = o1.getName().compareTo(o2.getName());
  28.                 if (num == 0)
  29.                 {
  30.                         return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
  31.                 }
  32.                 return -1;
  33.         }
  34. }

  35. class Student
  36. {
  37.         private String name;
  38.         private int age;
  39.         Student(String name,int age)
  40.         {
  41.                 this.name = name;
  42.                 this.age = age;
  43.         }
  44.         public int getAge()
  45.         {
  46.                 return age;
  47.         }
  48.         public String getName()
  49.         {
  50.                 return name;
  51.         }       
  52. }
复制代码
输出的结果是这样滴:
胡平燕3 29 湖南3
胡平燕3 50 湖南4
胡平燕2 23 湖南2
胡平燕1 21 null

什么原因呢 ??

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马