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

1. HashMap集合(键是Integer,值是String的案例)

2. 代码示例:

 1 package cn.itcast_02;
 2 
 3 import java.util.HashMap;
 4 import java.util.Set;
 5 
 6 /*
 7  * HashMap<Integer,String>
 8  * 键:Integer
 9  * 值:String
10  */
11 public class HashMapDemo2 {
12     public static void main(String[] args) {
13         // 创建集合对象
14         HashMap<Integer, String> hm = new HashMap<Integer, String>();
15 
16         // 创建元素并添加元素
17         // Integer i = new Integer(27);
18         // Integer i = 27;
19         // String s = "林青霞";
20         // hm.put(i, s);
21 
22         hm.put(27, "林青霞");
23         hm.put(30, "风清扬");
24         hm.put(28, "刘意");
25         hm.put(29, "林青霞");
26 
27         // 下面的写法是八进制,但是不能出现8以上的单个数据
28         // hm.put(003, "hello");
29         // hm.put(006, "hello");
30         // hm.put(007, "hello");
31         // hm.put(008, "hello");
32 
33         // 遍历
34         Set<Integer> set = hm.keySet();
35         for (Integer key : set) {
36             String value = hm.get(key);
37             System.out.println(key + "---" + value);
38         }
39 
40         // 下面这种方式仅仅是集合的元素的字符串表示
41         // System.out.println("hm:" + hm);
42     }
43 }

运行结果,如下:

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