Entry键值对对象。
在Map类设计时,提供了一个嵌套接口(static修饰的接口):Entry。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。
Entry为什么是静态的?
Entry是Map接口中提供的一个静态内部嵌套接口,修饰为静态可以通过类名调用。
Map集合遍历键值对方式:
Set<Map.Entry<K,V>> entrySet()
返回此映射中包含的映射关系的 Set 视图。
该方法返回值是Set集合,里面装的是Entry接口类型,即将映射关系装入了Set集合。
实现步骤:
1.调用Map集合中的entrySet()方法,将集合中的映射关系对象,存储到Set集合中。
2.迭代Set集合。
3.获取Set集合的元素,是映射关系的对象。
4.通映射关系对象的方法,getKey()和getValue(),获取键值对。
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "abc");
map.put(2, "bcd");
map.put(3, "cde");
map.put(4, "def");
map.put(5, "efg");
System.out.println(map);
//调用Map集合中的entrySet()方法,将集合中的映射关系对象,存储到Set集合中。
Set<Map.Entry<Integer, String>> set = map.entrySet();
//迭代Set集合。
Iterator<Entry<Integer, String>> it = set.iterator();
while(it.hasNext()){
//获取Set集合的元素,是映射关系的对象。
Map.Entry<Integer, String> entry= it.next();
//通映射关系对象的方法,getKey()和getValue(),获取键值对。
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
System.out.println("===================================================");
//增强for
for(Map.Entry<Integer, String> entry :map.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
运行结果:
{1=abc, 2=bcd, 3=cde, 4=def, 5=efg}
1
abc
2
bcd
3
cde
4
def
5
efg
===================================================
1
abc
2
bcd
3
cde
4
def
5
efg
另一个问题:增强for循环能否遍历Map?
答:
不能!!!!!
Iterable接口中并没有Map!!!!!
其实我们上面写增强for并不是遍历的Map,其实是遍历Set,间接遍历Map