首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Map.entry 跟Map.entrySet

2012-10-29 
Map.entry 和Map.entrySetpublic class MapTest {HashMap map new HashMap()public MapTest() {// 为简

Map.entry 和Map.entrySet
public class MapTest {
HashMap map = new HashMap();

public MapTest() {// 为简单起见,手动生成几个,如果采用生成器,更方便
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
map.put("5", "e");
}

public static void main(String[] args) {
MapTest mt = new MapTest();
for (Map.Entry entry : mt.map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}

Iterator it = mt.map.entrySet().iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

像上面的程序显示所示,Map.entry可以看作是Map.entrySet的一个对象,可以通过for循环取,也可以用迭代器取其中的元素。
Map.entrySet集合中就是map所存内容,每个Map.entryu对象都只是存储了他的索引,而不是实际的键和值。
在迭代中entry对象被用作数据的视窗,它只包含在静态字符串数组中的索引。在每次调用next方法时,index会递增指向下一个元素。

热点排行