首页 > 编程语言 > 详细

Java基础知识强化之集合框架笔记55:Map集合之HashMap集合(HashMap<String,Student>)的案例

时间:2015-10-09 21:19:52      阅读:265      评论:0      收藏:0      [点我收藏+]

1. HashMap集合(HashMap<String,Student>)的案例

HashMap是最常用的Map集合,它的键值对在存储时要根据键的哈希码来确定值放在哪里。

HashMap 中作为键的对象必须重写Object的hashCode()方法和equals()方法

2. 代码示例:

(1)Student.java:

 1 package cn.itcast_02;
 2 
 3 public class Student {
 4     private String name;
 5     private int age;
 6 
 7     public Student() {
 8         super();
 9     }
10 
11     public Student(String name, int age) {
12         super();
13         this.name = name;
14         this.age = age;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
 }

 

(2)代码测试类HashMapDemo3 

 1 package cn.itcast_02;
 2 
 3 import java.util.HashMap;
 4 import java.util.Set;
 5 
 6 /*
 7  * HashMap<String,Student>
 8  * 键:String    学号
 9  * 值:Student 学生对象
10  */
11 public class HashMapDemo3 {
12     public static void main(String[] args) {
13         // 创建集合对象
14         HashMap<String, Student> hm = new HashMap<String, Student>();
15 
16         // 创建学生对象
17         Student s1 = new Student("周星驰", 58);
18         Student s2 = new Student("刘德华", 55);
19         Student s3 = new Student("梁朝伟", 54);
20         Student s4 = new Student("刘嘉玲", 50);
21 
22         // 添加元素
23         hm.put("9527", s1);
24         hm.put("9522", s2);
25         hm.put("9524", s3);
26         hm.put("9529", s4);
27 
28         // 遍历
29         Set<String> set = hm.keySet();
30         for (String key : set) {
31             // 注意了:这次值不是字符串了
32             // String value = hm.get(key);
33             Student value = hm.get(key);
34             System.out.println(key + "---" + value.getName() + "---"
35                     + value.getAge());
36         }
37     }
38 }

运行效果,如下:

技术分享

 

Java基础知识强化之集合框架笔记55:Map集合之HashMap集合(HashMap<String,Student>)的案例

原文:http://www.cnblogs.com/hebao0514/p/4865092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!