Map泛型集合-顯示企鵝資訊
阿新 • • 發佈:2018-12-11
1 package collection; 2 3 /** 4 * 寵物類 5 * @author 6 * 7 */ 8 public class Pet { 9 private String name; 10 private String sex; 11 12 public Pet() { 13 } 14 15 public Pet(String name, String sex) { 16 this.name = name; 17 this.sex = sex; 18 }19 20 public String getName() { 21 return name; 22 } 23 public void setName(String name) { 24 this.name = name; 25 } 26 public String getSex() { 27 return sex; 28 } 29 public void setSex(String sex) { 30 this.sex = sex; 31 } 32 33 }
1package collection; 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 test4 { 9 10 public static void main(String[] args) { 11 Map<String,String> p=new HashMap<String,String>(); 12 p.put("歐歐","Q仔");13 p.put("亞亞","Q妹"); 14 p.put("菲菲","Q妹"); 15 p.put("美美","Q妹"); 16 17 System.out.println("使用Iteror遍歷,所有企鵝的暱稱和品種是:"); 18 Set<String> keys=p.keySet(); 19 //使用Iterator迭代器拿到每個key 20 Iterator<String> itor=keys.iterator(); 21 while(itor.hasNext()) { 22 String key=itor.next(); 23 String value=p.get(key); //根據key拿到value 24 System.out.println(key+"\t"+value); 25 } 26 27 System.out.println("使用foreach語句遍歷,所有企鵝的暱稱和品種分別是:"); 28 for (String key : keys) { 29 String value=p.get(key); 30 System.out.println(key+"\t"+value); 31 } 32 } 33 34 }