本帖最后由 Johnny_Hu 于 2015-4-14 20:15 编辑
- 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; 上面代码块中也有标注 哪位大神可以帮我讲解下 它们会在什么情况下有区别呢
|