首页 > 代码库 > 【泛型+集合框架】 两个简单的例程

【泛型+集合框架】 两个简单的例程

1 泛型的嵌套  泛型里面还是泛型

 

package package1;import java.util.HashMap;import java.util.Iterator;public class MapDemo {    public static void main(String[] args) {        HashMap<String , HashMap<String , String>> school =                new HashMap<String , HashMap<String , String>> ();                HashMap<String , String> room1 = new HashMap<String , String>();        HashMap<String , String> room2 = new HashMap<String , String>();                school.put("room1",room1);        school.put("room2",room2);        room1.put("01", "yang");        room1.put("02", "wang");        room2.put("01", "sun");        room2.put("02", "li");                Iterator<String> it1 = school.keySet().iterator();        while(it1.hasNext()){            String room = it1.next();            HashMap<String , String> roomm = school.get(room);            System.out.println(room + ":" + roomm);            getPersonInfo(roomm);                    }                            }    private static void getPersonInfo(HashMap<String, String> room) {        Iterator<String> it = room.keySet().iterator();        while(it.hasNext()){            String id = it.next();            String name = room.get(id);            System.out.println(id + ":" + name);        }    }}

 

运行结果:

room2:{01=sun, 02=li}
01:sun
02:li
room1:{01=yang, 02=wang}
01:yang
02:wang

 

 

 

 

 

 

2  泛型里面是封装好的类

package package6;import java.util.*;class Student2{    private String id;    private String name;    Student2(String id,String name){        this.id=id;        this.name=name;    }    public String toString(){        return id+"   ~~   "+name;    }}public class Test15 {    public static void main(String[] args){        HashMap<String,List<Student2>>qq=new HashMap<String,List<Student2>>();                List <Student2>room1=new ArrayList<Student2>();        List <Student2>room2=new ArrayList<Student2>();        qq.put("first", room1);        qq.put("second", room2);                room1.add(new Student2("01", "zhang"));        room1.add(new Student2("02", "wang"));        room2.add(new Student2("01", "yang"));        room2.add(new Student2("02", "chen"));                Iterator<String> it=qq.keySet().iterator();        while(it.hasNext()){            String roomName=it.next();            List<Student2> roomInfo=qq.get(roomName);            System.out.println(roomName);            getStudentInfo(roomInfo);        }    }            public static void getStudentInfo(List<Student2> list){        Iterator<Student2> it=list.iterator();        while(it.hasNext()){         Student2 s=it.next();            System.out.println(s);        }    }}

 

运行结果:

second
01 ~~ yang
02 ~~ chen
first
01 ~~ zhang
02 ~~ wang

 

【泛型+集合框架】 两个简单的例程