Fork me on GitHub

十五周课后习题

1.使用HashMap存储多个企鹅信息,然后统一使用Iterator进行遍历

 

 1 package Hmap;
 2 
 3 import java.util.HashMap;
 4 import java.util.Iterator;
 5 import java.util.Map;
 6 import java.util.Set;
 7 
 8 public class Test {
 9 
10     public static void main(String[] args) {
11         // TODO Auto-generated method stub
12         Map<String, String> map = new HashMap();
13         map.put("yaya", "Q妹");
14         map.put("feifei", "Q妹");
15         map.put("ouou", "Q仔");        
16         map.put("meimei", "Q妹");    
17         // System.out.println("iterator迭代器");
18         System.out.println("分别是:");
19         Set<String> nameset = map.keySet();
20         Iterator<String> iter = nameset.iterator();
21         while (iter.hasNext()){
22             String name = iter.next();
23             String sex = map.get(name);
24             System.out.println(name+"\t"+sex);
25         }
26         
27     }
28 
29 }

 

 

2.为企鹅添加一个编号,并作为键存储多个企鹅信息到应用泛型的HashMap集合 使用Iterator、foreach语句进行遍历

 

 1 package Hmap;
 2 
 3 import java.util.HashMap;
 4 import java.util.Iterator;
 5 import java.util.Map;
 6 import java.util.Set;
 7 
 8 public class Test {
 9 
10     public static void main(String[] args) {
11         // TODO Auto-generated method stub
12         Map<String, String> map = new HashMap();
13         map.put("yaya", "Q妹");
14         map.put("feifei", "Q妹");
15         map.put("ouou", "Q仔");
16         map.put("meimei", "Q妹");
17         // System.out.println("iterator迭代器");
18         System.out.println("分别是:");
19         System.out.println("使用iterator遍历");
20         Set<String> nameset = map.keySet();
21         Iterator<String> iter = nameset.iterator();
22         while (iter.hasNext()) {
23             String name = iter.next();
24             String sex = map.get(name);
25             System.out.println(name + "\t" + sex);
26         }
27 
28         System.out.println("使用foreach遍历");
29         for (String name : nameset) {
30             String sex = map.get(name);
31             System.out.println(name + "\t" + sex);
32         }
33     }
34 
35 }

 

posted @ 2020-06-12 16:10  世界丶已黑白  阅读(182)  评论(0编辑  收藏  举报