这是毕老师的基础视频的有一个练习题,是TreeMap的练习,以下是我写的代码:
- /*
- * 需求:对学生对象的年龄进行升序排序。
- *
- * 因为数据是以键值对形式存在的。
- * 所以要使用可以排序的Map集合。TreeMap
- */
- package com.haihang.MapDemo;
- import java.util.*;
- //学生类
- class Student implements Comparable<Student>{
- private String name;
- private int age;
-
- Student(String name,int age){
- this.name = name;
- this.age = age;
- }
-
- //让student类具有比较性顺序,一般用在二叉树原理的集合类
- public int compareTo(Student s){
- //按年龄进行排序
- int num = new Integer(this.age).compareTo(new Integer(s.age));
- if(num == 0)
- return this.name.compareTo(s.name);
- return num;
- }
-
- //复写哈希表
- public int hashCode(){
- return name.hashCode()+age*34;
- }
-
- public boolean equals(Object obj){
- if(!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
-
- Student st = (Student)obj;
- return this.name.equals(st.name) && this.age==st.age;
- }
-
- public String getName(){
- return name;
- }
-
- public int getAge(){
- return age;
- }
-
- }
- //设置比较器,对学生进行判断,确定学生唯一性
- class MyCompare implements Comparator<Student>{
- public int compare(Student obj1,Student obj2){
-
- int num= obj1.getName().compareTo(obj2.getName());
-
- if(num == 0){
- return new Integer(obj1.getAge()).compareTo(new Integer(obj2.getAge()));
- }
-
- return num;
- }
- }
- public class MapTest2 {
- public static void main(String[] args) {
- TreeMap<Student,String> tm = new TreeMap<Student, String>(new MyCompare());
-
- //添加元素
- tm.put(new Student("zhangsan1",19), "北京");
- tm.put(new Student("zhangsan2",30), "上海");
- tm.put(new Student("zhangsan3",20), "深圳");
-
- Set<Map.Entry<Student, String>> entrymap = tm.entrySet();
-
- Iterator<Map.Entry<Student, String>> it = entrymap.iterator();
-
- while(it.hasNext()){
- Map.Entry<Student, String> me = it.next();
- Student key = me.getKey();
- //System.out.println(key.getName()+":"+key.getAge()+":::"+me.getValue());
- System.out.println(key+":::"+me.getValue());
- }
- }
- }
复制代码
在最后一行代码中这样的书写System.out.println(key+":::"+me.getValue()); 得到的是这个结果:第一张图
但是在老师的教学视频中,运行处的结果是:第二张图
为什么会出现这样的状况呢? |
|