Map與List結合而成的強大的資料結構
阿新 • • 發佈:2018-12-30
package com.zhu.map; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; interface Pet{ } class Cat implements Pet{ public String toString(){ return "我是小貓"; } } class Dog implements Pet{ public String toString(){ return "我是小狗"; } } class Pig implements Pet{ public String toString(){ return "我是小豬"; } } public class MapOfList { public static void main(String[] args) { Map<String,List<? extends Pet>>map=new HashMap<String,List<? extends Pet>>(); map.put("張山", Arrays.asList(new Cat(),new Dog())); map.put("李四",Arrays.asList(new Dog(),new Pig())); map.put("王五",Arrays.asList(new Pig(),new Pig())); System.out.println("姓名:"+map.keySet()); System.out.println("寵物:"+map.values()); for(String name:map.keySet()){ System.out.print(name+": "); for(Pet pet:map.get(name)){ System.out.print(pet+" "); } System.out.println("\n"); } } }