java 18 -3 Map集合的键是String和自定义类的区别


HashMap:是基于哈希表的Map接口实现。
  哈希表的作用是用来保证键的唯一性的。

  HashMap<String,Person> 键是String,Integer等类的话,就会重写HashCode()和equals()方法,键的值一样,后面的就会覆盖前面的
  HashMap<Person,String> 键是自定义类的话,需要在自定义类中重写HashCode()和equals()方法,否则就算键的值一样,也会加进去的。

 1 package map_son;
 2 
 3 import java.util.HashMap;
 4 import java.util.Set;
 5 
 6 public class HashMapDemo1 {
 7 
 8     public static void main(String[] args) {
 9         
10         //首先看HashMap<String,String>
11         
12         //创建HashMap集合对象
13         HashMap<String , Person> hm = new HashMap<String,Person>();
14         
15         //创建Person对象的元素
16         Person s1 = new Person("阿三",27);
17         Person s2 = new Person("阿猫",29);
18         Person s3 = new Person("阿狗",27);
19         Person s4 = new Person("阿四",26);
20         Person s5 = new Person("阿狗",27);
21         
22         //添加键值对元素
23         hm.put("9527",s1);
24         hm.put("9522",s2);
25         hm.put("9524",s3);
26         hm.put("9529",s4);
27         hm.put("9529",s5);
28         
29         //遍历集合 
30         //首先获取键,再遍历,获取值,再输出键值对
31         Set<String> s = hm.keySet();
32         //遍历键集合
33         for(String key : s){
34             Person valus = hm.get(key);
35             System.out.println(key+"---"+valus.getName() + "-----" + valus.getAge());
36             /*    键的唯一性,Hash类集合的输出顺序,无规则。。
37                 9524---阿狗-----27
38                 9522---阿猫-----29
39                 9529---阿狗-----27
40                 9527---阿三-----27
41              */
42         }
43         System.out.println("-------------------------");
44         
45         
46         //HashMap<Person,String>     
47         //键是自定义类的话,需要在自定义类中重写HashCode()和equals()方法,否则就算键的值一样,也会加进去的。
48         
49         //创建集合对象
50         HashMap<Person,String> h = new HashMap<Person,String>();
51         
52         //把Person对象的元素当作键导入集合中,
53         h.put(s1, "9527");
54         h.put(s2, "9522");
55         h.put(s3, "9524");
56         h.put(s4, "9529");
57         h.put(s5, "9529");
58         
59         //遍历集合
60         //获取键集合
61         Set<Person> sp = h.keySet();
62         //遍历键集合
63         for(Person key : sp){
64             //获取值
65             String str = h.get(key);
66             System.out.println(str +"---"+key.getName()+"-----"+key.getAge());
67         }
68         /*    在自定义类中重写HashCode()和equals()方法,否则就算键的值一样,也会加进去的。
69              9529---阿四-----26
70             9527---阿三-----27
71             9522---阿猫-----29
72             9529---阿狗-----27
73          */
74     }
75 
76 }

 

posted @ 2016-09-25 22:15  卡拉瓦  阅读(1324)  评论(0编辑  收藏  举报