A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈波 中级黑马   /  2012-4-28 19:39  /  2501 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Set<Map.Entry<Student,String>> entrySet = tm.entrySet();

                Iterator<Map.Entry<Student,String>> it = entrySet.iterator();

                while(it.hasNext())
                {
                        Map.Entry<Student,String> me = it.next();

                        Student stu = me.getKey();
                        String addr = me.getValue();
                        System.out.println(stu+":::"+addr);
                }
        }
}

这个代码不是很理解 为什么这么写呢 大家帮忙解释一下

5 个回复

倒序浏览
可以这样理解:
Set是个文件夹,里面装的是结婚证(Map.Entry),结婚证上写着男方(键)和女方(值),Map.Entry代表了这样一种对应关系,并且是一个Map.Entry算一对关系。

评分

参与人数 1技术分 +1 收起 理由
职业规划-刘倩老师 + 1 很给力!

查看全部评分

回复 使用道具 举报
entrySet() 方法取得的值是 Set<Map.Entry<Student,String>>类型的,再Map.Entry<Student,String>看做一种类型数据,用迭代器对其进行迭代
然后就是取出对应的键和值。
回复 使用道具 举报
本帖最后由 光sail 于 2012-4-28 20:17 编辑

Set<Map.Entry<Student,String>> entrySet = tm.entrySet(); /*使用 tm.entrySet()方法获取set集合,集合里面放置的是映射的 collection 视图,键的类型是Student ,值是String         
*/
      Iterator<Map.Entry<Student,String>> it = entrySet.iterator(); //通过collection 视图的迭代器来获得映射项引用
                while(it.hasNext())
                {
                        Map.Entry<Student,String> me = it.next();

                        Student stu = me.getKey();  //获取Student类的对应的键
                        String addr = me.getValue();  ////获取String类的对应的值

                        System.out.println(stu+":::"+addr);
                }
        }
}

回复 使用道具 举报
由于Map中没有迭代器,只有将map转成set,才可以使用迭代器,而set集合底层使用的就是map集合。
Set<key> keySet():获取map集合中所有的键的set集合。之所以返回set,是因为键是有唯性。
Set<Map.Entry<key,value>> entrySet():获取map集合中的所有的关系对象。类型是Map.Entry。
回复 使用道具 举报
Set<Map.Entry<Student,String>> entrySet = tm.entrySet();//Map类对象tm调用entrySet方法,它的返回值类型是值个Set类型的泛型是Map.Entry类型对象,MapEntry类对象entrySet是使Map对象tm的键值存在某种关系的值。

                Iterator<Map.Entry<Student,String>> it = entrySet.iterator();//对Set集合对象entrySet进行迭代,这个迭代器泛型的是Set集合对象的泛型。

                while(it.hasNext())
                {
                        Map.Entry<Student,String> me = it.next();//设定Map.Entry对象me为指针

                        Student stu = me.getKey();//调用Map.Entry类方法getKey()返回的值类型为Map集合对象tm中的键。
                        String addr = me.getValue();//调用Map.Entry类方法getValue()返回的值类型为Map集合对象tm中的值。
                        System.out.println(stu+":::"+addr);
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马