毕老师的25天视频里面的第15天,Map联系里的。代码如下,我看了好久,明明写的和毕老师的一样,为什么他的运行结果是key是姓名和年龄,value是地址。而我的运行结果是这样的?C:\Users\yibo\Desktop
- import java.util.*;
- /*
- * 需求:每一个学生都有其对应的归属地
- * 学生:student 地址:String
- * 学生属性:姓名,年龄
- * 姓名和年龄相同视为同一个学生
- * 保证学生的唯一性
- * 将学生作为key,地址作为value存放。。。。因为一个地方可以有多个学生
- * 1.描述学生对象
- * 2.定义map集合
- * 3.获取map集合中的元素
- * */
- class MapText_学生归属地联系
- {
- public static void main(String[] args)
- {
- //Student stu1= new Student("zhangsan",20);
- //Student stu2= new Student("lisi",30);
- //Student stu3= new Student("wangwu",22);
- //Student stu4= new Student("zhaoliu",27);
-
- HashMap<Student,String> hm = new HashMap<Student,String>();
- hm.put(new Student("zhangsan",20),"beijing");
- hm.put(new Student("lisi",30),"nanjing");
- hm.put( new Student("wangwu",22),"jilin");
- hm.put(new Student("zhaoliu",27),"shanghai");
- Set<Student> keySet = hm.keySet();
- Iterator<Student> it = keySet.iterator();
- while(it.hasNext())
- {
- Student stu = it.next();
- String addr = hm.get(stu);
- System.out.println("key:"+stu+"..value:"+addr);
- }
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public int hashCode()
- {
- return name.hashCode()+age*34;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
- Student s = (Student)obj;
- return this.name.equals(s.name)&&this.age == s.age;
-
-
- }
- /*
- public int compareTo(Object obj)
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象,滚粗");
- Student s = obj;
- if(this.age==s.age)
- return this.name.compareTo(s.name);
- return 1;
-
- }
- */
- 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 String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码 |
|