【汎用+集合フレームワーク】2つの簡単なルーチン
6817 ワード
1汎型のネスト汎型の中はやはり汎型です
実行結果:
room2:{01=sun, 02=li}01:sun02:liroom1:{01=yang, 02=wang}01:yang02:wang
2汎用型はパッケージ化されたクラスです
実行結果:
second01 ~~ yang02 ~~ chenfirst01 ~~ zhang02 ~~ wang
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:sun02:liroom1:{01=yang, 02=wang}01:yang02: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);
}
}
}
実行結果:
second01 ~~ yang02 ~~ chenfirst01 ~~ zhang02 ~~ wang