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

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

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

HashMap的底层是利用hash算法算出键对应的哈希码,然后我们把存放在这个哈希码对应的存储位置。当我们需要取出这个值的时候,我们利用hash算法算出键对应的哈希码,然后就可以快速定位到哈希码对应的存储地方的值

哈希表结构主要作用:快速定位查找

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 }

运行效果,如下:

原文地址:https://www.cnblogs.com/hebao0514/p/4865092.html