Students st=new Students("王亮",18);
Map<Object, Object> ma=new HashMap();
ma.put(null, "1223");
ma.put("age", 20);
ma.put("name", st);
ma.put("st", st);
//方式一:
// Set<Object> ks= ma.keySet();
// Iterator<Object> it = ks.iterator();
// while(it.hasNext()){
// Object u=it.next();
// System.out.println(u+":"+ma.get(u));
// }
//方式二:
for (Map.Entry<Object, Object > m : ma.entrySet()){
{
Object key = m.getKey();
Object value = m.getValue();
System.out.println(key+":"+value);
}
主要是对方式二的解读:
//方式二:
for (Map.Entry<Object, Object > m : ma.entrySet()){//通过Entry<k,v>方法,获得映射表映射项(键-值对)。Map.entrySet 方法返回映射的 collection 视图,其中的元素属于此类。也即是这行代码的结构是for(变量类型 变量X:遍历对象)。
{
Object key = m.getKey();
Object value = m.getValue();
System.out.println(key+":"+value);
}