hashMap遍历方式
package Ch17; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Created by liwenj on 2017/7/28. */ public class MapTest1 { public static void main(String[] args) { HashMap<String,Dog> hashMap = new HashMap<>(); Dog dog1 = new Dog("胡了", "泰迪"); Dog dog2 = new Dog("美美", "泰迪"); Dog dog3 = new Dog("佳佳", "泰迪"); hashMap.put("胡了", dog1); hashMap.put("美美", dog2); hashMap.put("佳佳", dog3); // boolean set = hashMap.containsKey("莎莎"); // if(set==false){ // throw new InputMismatchException("没有这个名字的狗狗"); // } // System.out.println(set); System.out.println("for循环增强遍历"); Set<String> keys = hashMap.keySet(); for (Object O : keys) { System.out.println(O + "\t" + hashMap.get(O)); } System.out.println("迭代器遍历"); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key = (String) it.next(); System.out.println(key + "\t" + hashMap.get(key)); } System.out.println("entryset方式遍历"); Set<Map.Entry<String, Dog>> entries = hashMap.entrySet(); for(Map.Entry<String,Dog> entry:entries){ System.out.println(entry.getKey()+"\t"+entry.getValue()); } } }