一对多:
一个教室对应多个学生.
学校里边不同的班级有不同的学生,但是可能ID相同.
//优化过后的代码,更具有复用和扩展性.
//定义一个可以存放三个数据的集合——班级名称,学生ID,学生名称
import java.util.*;
class MyMap
{
private Map map;
MyMap()
{
map = new HashMap();
}
public void createClass(String className, String id, String name)
{
Map subMap = (Map)map.get(className);
if (subMap == null)
{ subMap = new HashMap();
map.put(className, subMap); //已经存在班级,只需要向学生这个Map集合里边存数据,而班级的Map不需要再存了
}
subMap.put(id, name);
}
public String getName(String className, String id)
{
Map subMap = (Map)map.get(className);
return (String)subMap.get(id);
}
public void getStudent(String className)
{
System.out.println(className);
Map subMap = (Map)map.get(className);
Set mySet = subMap.keySet();
for (Iterator it = mySet.iterator(); it.hasNext(); )
{
String id = (String)it.next();
String name = (String)subMap.get(id);
System.out.println(id + "..." + name);
}
}
public void getAll()
{
Set set1 = map.keySet();
for (Iterator it = set1.iterator(); it.hasNext(); )
{
String className = (String)it.next();
System.out.println(className);
Map subMap = (Map)map.get(className);
Set set2 = subMap.keySet();
for (Iterator it1 = set2.iterator(); it1.hasNext(); )
{
String id = (String)it1.next();
String name = (String)subMap.get(id);
System.out.println(it + "..." + name);
}
}
}
}
class MyMapDemo
{
public static void main(String[] args)
{
MyMap mm = new MyMap();
mm.createClass("班级一", "01", "小张");
mm.createClass("班级一", "02", "小王");
mm.createClass("班级一", "03", "小李");
mm.createClass("班级二", "01", "小A");
mm.createClass("班级二", "02", "小B");
mm.createClass("班级二", "03", "小C");
//System.out.println(mm.getName("班级一", "02"));
//mm.getStudent("班级一");
//mm.getStudent("班级二");
mm.getAll();
}
}
//前期设计代码,不具备扩展性和复用性.
import java.util.*;
class MapDemo
{
public static void main(String[] args)
{
//初期设计————(代码缺少复用性,冗余)
//定义一个学校,里边可以有多个班级
HashMap <String, HashMap> school = new HashMap<String, HashMap>();
//班级一
HashMap<String, String> class1 = new HashMap<String ,String>();
class1.put("01", "小张");
class1.put("02", "小王");
class1.put("03", "小李");
//班级二
HashMap<String, String> class2 = new HashMap<String ,String>();
class2.put("01", "小周");
class2.put("02", "小孙");
class2.put("03", "小赵");
school.put("班级一", class1);
school.put("班级二", class2);
show(school);
}
public static void show(Map map)
{
Set<String> s = map.keySet();
for (Iterator<String> it = s.iterator(); it.hasNext(); )
{
String className = it.next();
System.out.println(className);
Map hs = (Map)map.get(className);
Set <String> s1 = hs.keySet();
for (Iterator <String> it1 = s1.iterator(); it1.hasNext(); )
{
String id = it1.next();
String name = (String)hs.get(id);
System.out.println(id+".."+name);
}
}
}
}