java基础 TreeMap的应用

发布时间:2014-10-23 23:23:21
来源:分享查询网

package www.file.com; import java.util.*;     //集合框架中必须导入java.util.* 包 import java.util.Map.Entry;   /* 需求:自定义学生类,按照学生的姓名排序,姓名一致的时候按照年龄大小排序   */   class StuM implements Comparable<StuM> {//使学生类具备比较性  String name;  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;  } //构造函数,便于初始化  StuM(String name, int age) {   this.age = age;   this.name = name;  }  public int compareTo(StuM s) {   int num = new Integer(this.age).compareTo(new Integer(s.age));   if (num == 0) {    return this.name.compareTo(s.name);   }   return num;  }  public String toString() {   return name + ":: " + age + "  :: ";  }  public boolean equals(Object obj) {   if (!(obj instanceof StuM))    throw new RuntimeException("该类不是 StuM类,不具备比较性");   StuM stu = (StuM) obj;   return this.name.equals(stu.name) && this.age == stu.getAge();  }  public int hashCode() {   return name.hashCode() + age * 34;  } } class BJName implements Comparator<Object> {  @Override  public int compare(Object o1, Object o2) {   // TODO Auto-generated method stub   StuM stu1 = (StuM) o1;   StuM stu2 = (StuM) o2;   int num = stu1.getName().compareTo(stu2.getName()); //按姓名排序,字符串自身具备比较性   if (num == 0) {  //当姓名一样的时候,按照年龄大小排序    if (stu1.getAge() > stu2.getAge())     return -1;    if (stu1.getAge() == stu2.getAge())     return 0;    else     return 1;   }   return num;  } } public class DemoTest002 {  /**   * @param args   */  public static void main(String[] args) {   // TODO Auto-generated method stub   Map<StuM, String> map = new TreeMap<StuM, String>(new BJName());   map.put(new StuM("lisi2", 11), "北京");   map.put(new StuM("blisi", 12), "北京");   map.put(new StuM("alisi", 13), "北京");//标号1   map.put(new StuM("blisi", 12), "北京");   map.put(new StuM("alisi", 13), "天津");  //标号2   //map 键值对中,键是唯一的,所以标号2会覆盖标号1的值     for (Entry<StuM, String> s : map.entrySet()) {   //高级for循环格式:for(类型  自定义变量名:集合)    System.out.println(s);   }  } }

返回顶部
查看电脑版