复制代码
- import java.util.*;
- public class MapDemo1 {
- public static void main(String[] args)
- {
- Map<Student, String> stuMap = new HashMap<Student, String>();
- stuMap.put(new Student("胡平燕1", 21),"湖南1");
- stuMap.put(new Student("胡平燕2", 23),"湖南2");
- stuMap.put(new Student("胡平燕3", 50),"湖南4");
- stuMap.put(new Student("胡平燕3", 29),"湖南4");
- stuMap.put(new Student("胡平燕3", 29),"湖南3");
- //keySet取出方式
- Set<Student> keySet = stuMap.keySet();
- for(Iterator<Student> it = keySet.iterator(); it.hasNext();)
- {
- Student key = it.next();
- String name= stuMap.get(key);
- System.out.println(key.getName()+" "+key.getAge()+" "+name);
- }
- //entrySet取出方式
- Set<Map.Entry<Student, String>> entrySet = stuMap.entrySet();
- for(Iterator<Map.Entry<Student, String>> iter = entrySet.iterator(); iter.hasNext();)
- {
- Map.Entry<Student, String> me = iter.next();
- Student stu = me.getKey();
- String addr = me.getValue();
- System.out.println(stu.getName()+"----"+stu.getAge()+"----"+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 getAge()
- {
- return age;
- }
- public String getName()
- {
- return name;
- }
- @Override
- 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 this.name.hashCode()+age*13;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
- Student s = (Student)obj;
- //下面这两句 不管我写哪句 程序输出正确 没报错
- //哪位大神可以帮我讲解下 它们会在什么情况下有区别呢
- return this.getName().equals(s.getName()) && this.getAge() == s.getAge();
- return this.name.equals(s.name) && this.age == s.age;
- }
- }
//下面这两句 不管我写哪句 程序输出正确 没报错//哪位大神可以帮我讲解下 它们会在什么情况下有区别呢
return this.getName().equals(s.getName()) && this.getAge() == s.getAge();
return this.name.equals(s.name) && this.age == s.age;上面代码块中也有标注哪位大神可以帮我讲解下 它们会在什么情况下有区别呢
lwj123 发表于 2015-4-14 20:22
你的意思是说compareTo的问题吗?
我的理解是这样的,你是不管输入这两句话任意一句都没有用是吧:
return ...
小丸子 发表于 2015-4-14 22:15
学习了,楼主细节挖的很深!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |