import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class Test{
public static void main(String[] args){
Map hashMap=new HashMap();
hashMap.put("key1",new String("value1"));
hashMap.put("key2",new String("value2"));
hashMap.put("key3",new String("value3"));
hashMap.put("key4",new String("value4"));
hashMap.put("key5",new String("value5"));
//创建HashMap对象并填充键-值
Iterator it=hashMap.entrySet().iterator();
//使用entrySet方法将hashMap转化为Set视图,返回的Set中的每个元素都是一个Map.Entry
while(it.hasNext()){
Map.Entry entry=(Map.Entry)it.next();
//Map.Entry可以看成是一种特殊的Map,与Map不同的是Map.Entry只能含有一对键-值
String key=(String)entry.getKey();
String value=(String)entry.getValue();
System.out.println("key:"+key+" value:"+value);
}
}
}
运行结果:
key:key1 value:value1
key:key3 value:value3
key:key5 value:value5
key:key2 value:value2
key:key4 value:value4
JDK 1.5
Map m = new HashMap();
for (Object o : map.keySet()) {
map.get(o);
}
JDK1.4
Map map = new HashMap() ;
Iterator it = map.entrySet().iterator() ;
while (it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next() ;
Object key = entry.getKey() ;
Object value = entry.getValue() ;
}
阅读(5937) | 评论(0) | 转发(0) |