之前我說過《集合嵌套之ArrayList嵌套ArrayList》,那么HashMap嵌套HashMap該怎么寫呢?其實真的不難,就跟雙層for循環是一個意思,接下來,我們通過一個案例來演示HashMap嵌套HashMap,看如下代碼程序:
package cn.edu.jit.map;import java.util.HashMap;import cn.edu.jit.bean.Student;/** * 集合嵌套之HashMap嵌套HashMap * * 需求: * 雙元課堂有很多基礎班 * 第88期基礎班定義成一個雙列集合,鍵是學生對象,值是學生的歸屬地(值可以重復的) * 第99期基礎班定義成一個雙列集合,鍵是學生對象,值是學生的歸屬地(值可以重復的) * * 無論88期還是99期都是班級對象,所以為了便于統一管理,把這些班級對象添加到雙元課堂集合中。 * @author Rocky * */public class HashMapHMDemo { public static void main(String[] args) { //定義88期基礎班 HashMap<Student, String> hm88 = new HashMap<Student, String>(); hm88.put(new Student("張三",23), "北京"); hm88.put(new Student("李四",24), "北京"); hm88.put(new Student("王五",25), "上海"); hm88.put(new Student("趙六",26), "廣州"); hm88.put(new Student("錢七",27), "深圳"); //定義99期基礎班 HashMap<Student, String> hm99 = new HashMap<Student, String>(); hm99.put(new Student("唐僧",1023), "北京"); hm99.put(new Student("孫悟空",1024), "北京"); hm99.put(new Student("豬八戒",1025), "上海"); hm99.put(new Student("沙和尚",1026), "廣州"); //定義雙元課堂 HashMap<HashMap<Student, String>, String> hm = new HashMap<HashMap<Student, String>, String>(); hm.put(hm88, "第88期基礎班"); hm.put(hm88, "第99期基礎班"); //遍歷雙列集合 for (HashMap<Student, String> h : hm.keySet()) {//hm.keySet()代表的是雙列集合中的鍵的集合 String value = hm.get(h);//get(h)根據鍵對象獲取值對象 //遍歷鍵的雙列集合對象 for (Student key : h.keySet()) {//h.keySet()是獲取集合中所有的學生鍵對象 String value2 = h.get(key); System.out.PRintln(key + "=" + value2 + "=" + value); } } }}今天集合嵌套就介紹到這,本文中所有的案例程序都是本人親測過,如有不對的地方請各位朋友歡迎指正,謝謝了!
新聞熱點
疑難解答