1.问题:
Map集合的遍历:
2.源代码:
(拷贝可直接运行,建议自己敲一遍)
public class MapForeach {
public static void main(String[] args) {
Map<String,String> map=new HashMap<String,String>();
map.put("1","A");
map.put("2","B");
map.put("3","C");
map.put("4","D");
map.put("5","E");
map.put("6","F");
for (Map.Entry<String,String> entry:map.entrySet()){
System.out.println(entry.getKey()+"---------->"+entry.getValue());
}
}
}
3.截图:
4.总结:
其实很简单;我们来看看源码:
/**
* A map entry (key-value pair). The <tt>Map.entrySet</tt> method returns
* a collection-view of the map, whose elements are of this class. The
* <i>only</i> way to obtain a reference to a map entry is from the
* iterator of this collection-view. These <tt>Map.Entry</tt> objects are
* valid <i>only</i> for the duration of the iteration; more formally,
* the behavior of a map entry is undefined if the backing map has been
* modified after the entry was returned by the iterator, except through
* the <tt>setValue</tt> operation on the map entry.
* @see Map#entrySet()
* @since 1.2
*/
interface Entry<K,V> {
/**
* Returns the key corresponding to this entry.
* @return the key corresponding to this entry
* @throws IllegalStateException implementations may, but are not
* required to, throw this exception if the entry has been
* removed from the backing map.
*/
一个Map的Entry就是一个Key-Value键值对;而EntrySet方法返回的是一个map的视图集合,其元素就是其类,唯一包含与map entry相关的是用迭代器;Map.Entry对象仅可以通过迭代器来获得;更确切地说,如果返回的map在entry被迭代器返回之前被改变了,map entry的行为是未定义的,除非通过setValue对map entry进行操作;