本帖最后由 changchunhaha 于 2014-4-3 14:39 编辑
- import java.util.*;
- class MapEntry
- {
- public static void main(String[] args)
- {
- Map<Student,String> m = new HashMap<Student,String>();
- m.put(new Student("zhangsan01",21),"shanghai");
- m.put(new Student("zhangsan02",22),"beijing");
- m.put(new Student("zhangsan03",23),"wuhan");
- m.put(new Student("zhangsan04",24),"tianjin");
-
- Set<Map.Entry<Student,String>> sme = m.entrySet();//我不明白泛型在这是怎么应用的?求大神帮助!!
- Iterator<Map.Entry<Student,String>> it = sme.iterator();//我不明白泛型在这是怎么应用的?
- while(it.hasNext())
- {
- Map.Entry<Student,String> me = it.next();
- Student stu = me.getKey();
- String addr = me.getValue();
- System.out.println(stu+"............"+addr);
- }
- }
- }
- class Student
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
-
- public int hashCode()
- {
- return name.hashCode()+age*30;
- }
-
- 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(Student s) //还有这个compareTo的代码不是太明白,有点读不懂,谁能帮忙说一下原理走向。谢谢!!!
- {
- 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;
- }
- }
复制代码
|