为什么用Set来装HashMap的数据,跟多态也没关系吧,Set继承至接口Collection,,,,HashMap继承至接口Map,,,,而且Map还是独立的接口
例如我定义个 : HashMap<String,Student> hm = new HashMap<String,Student>(); //创建集合对象
Student s1 = new Student("星矢","天马流星拳","青铜圣斗士");// 创建元素对象
Student s2 = new Student("紫龙","庐山升龙霸","青铜圣斗士");
Student s3 = new Student("沙加","天舞宝轮","黄金圣斗士");
Student s4 = new Student("童虎","庐山百龙霸","黄金圣斗士");
hm.put("itheima001", s1); //4: 添加元素到集合
hm.put("itheima002", s2);
hm.put("itheima003", s3);
hm.put("itheima004", s4);
// 遍历
// a: 获取所有的 键
Set<String> ids = hm.keySet();
// b: 获取到每一个 键
for (String ids) {
// c: 通过 键 找到 对应的 值
Student s = hm.get(id);
//d: 打印, 通过值(学生), 得到学生的具体信息
//打印的结果: 编号,姓名,绝招,圣衣
System.out.println(id + ", " + s.getName() + ", " + s.getSkill() + ", " + s.getClazz());
}
}
}
|
|