使用HashMap存储多个企鹅信息,然后统一使用Iterator进行遍历 package JDBCdemo; 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); } } } 为企鹅添加一个编号,并作为键存储多个企鹅信息到应用泛型的HashMap集合 使用Iterator、foreach语句进行遍历 package JDBCdemo; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class mma { public static void main(String[] args) { Map<String,String> map=new HashMap(); map.put("欧欧","Q仔"); map.put("亚亚","Q妹"); map.put("美美","Q妹"); map.put("菲菲","Q妹"); System.out.println("使用Iterator遍历,企鹅的昵称和品种分别是:"); Set<String> keyset = map.keySet(); Iterator<String> iter = keyset.iterator(); while(iter.hasNext()){ String key=iter.next(); String value=map.get(key); System.out.println(key+" "+value); } System.out.println("使用foreach遍历,所有企鹅的昵称和品种分别是:"); for (String key : keyset) { String sex = map.get(key); System.out.println(key + " " + sex); } } }