Map.Entry是Map内部定义的一个接口,专门用来保存key→value的内容。
Map.Entry的定义如下:
public static interface Map.Entry<K,V>
Map.Entry是使用static关键字声明的内部接口,此接口可以由外部通过"外部类.内部类"的形式直接调用。
Map类提供了一个称为entrySet()的方法,这个方法返回一个Map.Entry实例化后的对象集。
Map.Entry类提供了一个getKey()方法和一个getValue()方法分别获取key---value的值。
Map.Entry同时也提供了一个setValue()方法,程序员可以使用它修改map里面的值。
例:
Random r=new Random();
HashMap<String,Integer> ml = new HashMap<String,Integer>();
m1.put("a",r.nextInt(100));
m1.put("b",r.nextInt(100));
m1.put("c",r.nextInt(100));
m1.put("d",r.nextInt(100));
for(Map.Entry<String,Integer> e : m.entrySet()) {
System.out.println("key:" + e.getKey() + "value:" + e.getValue());
}
Iterator iter = map.enrtySet().iterator();
while(iter.hasNext()){
Map.Entry<String,Integer> ent = (Map.Entry<String,Integer>)itor.next();
System.out.println("key:" + ent.getKey() + "value:" + ent.getValue());
}
}