增强for循环:
增强for循环只能遍历数组和实现了Iteratable接口的对象。
语法:
for(元素的类型 变量名:数组或实现了Iteratable接口的对象){
System.out.println(变量名);
}
增强for循环的特点:只适合取数据。要想在遍历时改元素的值,请使用传统for循环。
遍历MAP的四种方法:
//增强for循环
public class Demo {
//传统方式遍历Map
@Test
public void test3(){
Map map = new LinkedHashMap();
map.put("a", "aaa");
map.put("b", "bbb");
map.put("c", "ccc");
Set keys = map.keySet();
Iterator it = keys.iterator();
while(it.hasNext()){
String key = (String)it.next();
String value = (String) map.get(key);
System.out.println(key+"="+value);
}
}
@Test//增强for遍历map方式一
public void test31(){
Map map = new LinkedHashMap();
map.put("a", "aaa");
map.put("b", "bbb");
map.put("c", "ccc");
Set keys = map.keySet();
for(Object obj:keys){
String key = (String)obj;
String value = (String) map.get(key);
System.out.println(key+"="+value);
}
}
//传统方式遍历Map
@Test
public void test4(){
Map map = new LinkedHashMap();
map.put("a", "aaa");
map.put("b", "bbb");
map.put("c", "ccc");
Set me = map.entrySet();
Iterator it = me.iterator();
while(it.hasNext()){
Map.Entry m = (Map.Entry)it.next();
String key = (String) m.getKey();
String value = (String)m.getValue();
System.out.println(key+"="+value);
}
}
@Test//增强for循环遍历map方式二
public void test41(){
Map map = new LinkedHashMap();
map.put("a", "aaa");
map.put("b", "bbb");
map.put("c", "ccc");
for(Object obj:map.entrySet()){
Map.Entry me = (Map.Entry )obj;
String key = (String) me.getKey();
String value = (String)me.getValue();
System.out.println(key+"="+value);
}
}
}