Newbie蔡  

存储在HashMap集合中的元素,必须覆盖hashCode和equals方法(与HashSet类似)

 

 

 1 import java.util.HashMap;
 2 import java.util.Iterator;
 3 
 4 import cn.itcast.p2.bean.Student;
 5 
 6 public class HashMapDemo {
 7 
 8     public static void main(String[] args) {
 9         /*
10          * 将学生对象和学生的归属地通过键与值存储到map集合中
11          */
12         HashMap<Student,String> hm = new HashMap<Student,String>();
13         
14         hm.put(new Student("lisi",38), "北京");
15         hm.put(new Student("zhaoliu",24), "上海");
16         hm.put(new Student("xiaoqiang",31), "沈阳");
17         hm.put(new Student("wangcai",38), "大连");
18         hm.put(new Student("zhaoliu",24), "铁岭");
19         
20         Iterator<Student> it = hm.keySet().iterator();
21         while (it.hasNext())
22         {
23             Student key = it.next();
24             String value = hm.get(key);
25             System.out.println(key.getName()+":"+key.getAge()+"--"+value);
26         }
27 
28     }
29 
30 }

 

posted on 2016-09-05 14:46  Newbie蔡  阅读(399)  评论(0编辑  收藏  举报