Map map = new LinkedHashMap();
map.put("1","aaa");
map.put("2","bbb");
map.put("3","ccc");
传统方式1
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
String key = (String)it.next();
String value = (String) map..get(key);
System.out.println(key + "=" + value);
}
传统方式2
Set set = map.entrySet();
Iterator it = set.iterator();
while(it.hasNext()){
Map.Entry entry =(Entry)it.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "=" + value);
}
通过增强for循环的两种方式:
1:
Set set = map.keySet();
for(Object obj:set){
String key = (String)obj;
String value = (String)map.get(key);
System.out.println(key + "=" +value);
}
2
Set set = map.entrySet();for(Object obj:set){
Map.Entry entry = (Entry)obj;
String key = (String)entry.getKey();
String value = (String)entry.getValue();
System.out.println(key + "=" +value);
}
增强for循环需要:继承自集合类或者实现集合接口。
增强for循环只能用于取值,不能用于修改值。
如:List list = new List();
list.add("1");
for(Object obj:list){
obj = 10;
}
obj只是一个拿到list值的变量,不能通过它修改list的值。