public static void main(String[] args) { /** * 创建多个狗狗对象 */ Dog ououDog = new Dog("欧欧","雪纳尔"); Dog yayaDog = new Dog("丫丫","拉布拉多"); Dog meimeiDog = new Dog("美美","雪纳尔"); /** * 创建Map集合对象并把多狗狗对象放入其中 */ Map<String,Dog>dogMap = new HashMap<String,Dog>(); dogMap.put(ououDog.getName(), ououDog); dogMap.put(yayaDog.getName(), yayaDog); dogMap.put(meimeiDog.getName(), meimeiDog); //3.通过迭代器依次输出集合中所有狗狗的信息 System.out.println("使用iteration遍历,所有狗狗的昵称和品种分别是:"); //set w Set<String>keys = dogMap.keySet(); //取出所有key的集合 //System.out.println(keys); //欧欧 丫丫 美美 Iterator<String>it = keys.iterator();//获取iterator对象 while(it.hasNext()){ //判断是否有下一个 String key = it.next(); //取出key Dog dog = dogMap.get(key);//get写值 打出 key所对应的values System.out.println(key+" "+dog.getPack()); } Set<Entry<String,Dog>> entrySet=dogMap.entrySet(); for (Entry<String,Dog>entry:entrySet) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); } }