欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入 * 结果yingyong这个key对应的value集合是null * 遍历Map的时候还会出现空指针错误 */ //jiSuanJi.put("yingyong", (Map) new HashMap()。put("01", "haha")); //jiSuanJi.put("yingyong",
欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
* 结果yingyong这个key对应的value集合是null
* 遍历Map的时候还会出现空指针错误
*/
//jiSuanJi.put("yingyong", (Map) new HashMap()。put("01", "haha"));
//jiSuanJi.put("yingyong", (Map) new HashMap()。put("02", "xixi"));
/*
* 要使用下面这种方式,先把集合定义好,
* 把映射关系设置好,再去给集合添加元素
*/
jiSuanJi.put("ruanJian", ruanJian);
jiSuanJi.put("wangZhan", wangZhan);
ruanJian.put("01", "zhangsan");
ruanJian.put("02", "lisi");
wangZhan.put("01", "zhaoliu");
wangZhan.put("02", "zhouqi");
Set keySet = jiSuanJi.keySet();
for(Iterator it = keySet.iterator();it.hasNext();) {
String key = it.next();
System.out.println(key);
Map map = jiSuanJi.get(key);
Set> entrySet = map.entrySet();
for(Iterator> it2 = entrySet.iterator();it2.hasNext();) {
Map.Entry me = it2.next();
System.out.println(me.getKey() + "" + me.getValue());
}
}
}
/*
* 这种把班级和学生做了映射
* 学生类中封装了学号和姓名
*/
public static void oneToList() {
Map> jiSuanJi = new HashMap>();
List ruanJian = new ArrayList();
List wangZhan = new ArrayList();
jiSuanJi.put("ruanJian", ruanJian);
jiSuanJi.put("wangZhan", wangZhan);
ruanJian.add(new PersonDemo("01","zhangsan"));
ruanJian.add(new PersonDemo("02","lisi"));
wangZhan.add(new PersonDemo("01","wangwu"));
wangZhan.add(new PersonDemo("02","zhaoliu"));
Set keySet = jiSuanJi.keySet();
for(Iterator it = keySet.iterator();it.hasNext();){
String key = it.next();
System.out.println(key);
List list = jiSuanJi.get(key);
for(Iterator it2 = list.iterator();it2.hasNext();) {
PersonDemo pd = it2.next();
System.out.println(pd);
}
}
}
}
class PersonDemo {
private String id;
private String name;
public PersonDemo(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.id + "…" + this.name;
}
}
[1] [2]