本帖最后由 陈中岩 于 2013-4-12 18:33 编辑
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- /**练习
- * 每一个学生都有对应的归属地。
- * 学生Student,地址String.
- * 学生属性:姓名,年龄。
- * 注意:姓名和年龄相同的视为同一个学生.
- * 保证学生的唯一性.
- *
- * @author Chen_zyan
- *
- * 1,描述学生。
- * 2,定义map容器,将学生作为键,地址作为值。存入.
- * 3,获取map集合中的元素.
- */
- //注意,以后写的时候一定要做这几个动作:1,实现Comparable,2,覆盖hashCode与equals方法
- //定义学生,因为有可能会存储到二叉树当中,所以要覆写二叉树方法,实现Comparable
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- //覆写
- 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*22;
- }
- 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 String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class MapTest1 {
- public static void main(String[] args)
- {
- HashMap<Student,String> hm = new HashMap<Student,String>();
-
- hm.put(new Student("lisi1",21),"beijing");
- hm.put(new Student("lisi2",22),"shanghai");
- hm.put(new Student("lisi3",23),"nanjing");
- hm.put(new Student("lisi4",24),"wuhan");
-
- //第一种取出方式keySet
- 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(stu+"...."+addr);
- }
-
- //第二种取出方式
-
- Set<Map.Entry<Student, String>> entrySet = hm.entrySet();
-
- Iterator<Map.Entry<Student, String>> iter = entrySet.iterator();
-
- while(iter.hasNext())
- {
- Map.Entry<Student, String> map = iter.next();
- Student stu = map.getKey();
- String addrs = map.getValue();
- System.out.println(stu+"............"+addrs);
- }
- }
- }
复制代码 下面是我输出的结果
test.Student@62363cc....beijing
test.Student@62363fa....nanjing
test.Student@6236411....wuhan
test.Student@62363e3....shanghai
test.Student@62363cc............beijing
test.Student@62363fa............nanjing
test.Student@6236411............wuhan
test.Student@62363e3............shanghai
下面是我想要的输出结果
lisi1:21....beijing
lisi1:21............beijing
|