import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class text { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("亚亚", "Q妹"); map.put("菲菲", "Q妹"); map.put("欧欧", "Q仔"); map.put("亚亚", "Q妹"); map.put("美美", "Q妹"); System.out.println("使用Iterator遍历,所有企鹅的昵称和品种分别是:"); Set<String> keyset = map.keySet(); Iterator<String> it = keyset.iterator(); while (it.hasNext()) { String key = it.next(); String value = map.get(key); System.out.println(key + " " + value); } System.out.println("使用foreach遍历,所有企鹅的昵称和品种分别是:"); for (String in : map.keySet()) { String str = map.get(in); System.out.println(in + " " + str); } } }
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class text2 { public static void main(String[] args) { Map<Integer,Penguin> map1 = new HashMap<Integer,Penguin>(); Penguin a1 = new Penguin("欧欧","Q仔"); Penguin a2 = new Penguin("亚亚","Q妹"); Penguin a3 = new Penguin("美美","Q妹"); Penguin a4 = new Penguin("菲菲","Q妹"); map1.put(1, a1); map1.put(2, a2); map1.put(3, a3); map1.put(4, a4); System.out.println("使用foreach遍历,所有企鹅的昵称和品种分别是:"); for (Integer in : map1.keySet()) { Penguin str = map1.get(in); System.out.println(in + " " + str.getName()+ " " +str.getSex()); } System.out.println("使用Iterator遍历,所有企鹅的昵称和品种分别是:"); Set<Integer> key = map1.keySet(); Iterator<Integer> it1 = key.iterator(); while (it1.hasNext()) { Integer key1 = it1.next(); Penguin value = map1.get(key1); System.out.println(key1 + " " + value.getName()+ " " +value.getSex()); } } }