java6.12

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

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

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

package pro2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Test {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap();
        map.put("yaya", "Q妹");
        map.put("feifei", "Q妹");
        map.put("ouou", "Q仔");
        map.put("meimei", "Q妹");
        System.out.println("分别是:");
        System.out.println("使用iterator遍历");
        Set<String> nameset = map.keySet();
        Iterator<String> iter = nameset.iterator();
        while (iter.hasNext()) {
            String name = iter.next();
            String sex = map.get(name);
            System.out.println(name + "\t" + sex);
        }
        System.out.println("使用foreach遍历");
        for (String name : nameset) {
            String sex = map.get(name);
            System.out.println(name + "\t" + sex);
        }
    }
}

 

posted @ 2020-06-12 16:42  潘宇航  阅读(136)  评论(0编辑  收藏  举报