JDK5.0相比JDK4.0新增特性之一:增强for循环,只能用在数组和实现Iterable接口的集合类上,所以对于集合类来说,List、Set类可以使用增强for循环实现快速操作,而map类不能,只能通过set类来中间转换,如图:
第一种方式:
第二种方式:
通过程序测试实现:
package Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Test;
/**
* 增强for循环:在集合中的应用
* @author USER
*
*/
public class TestFor {
//List中
@Test
public void test1() {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
for (Object object : list) {
int m = (int) object;
System.out.println(m);
}
}
//Map:由于map没有实现Iterator接口,所以只能通过set方式进行迭代
//传统方式一
@Test
public void test2(){
Map map = new LinkedHashMap();//LinkedHashMap与存储循序一致
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
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);
}
}
//增强for方式一
@Test
public void test3(){
Map map = new LinkedHashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
for (Object object : map.keySet()) {
String key = (String) object;
String value = (String) map.get(key);
System.out.println(key+"="+value);
}
}
//传统方式二
@Test
public void test4() {
Map map = new LinkedHashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
Set set = map.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Entry) it.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key+"="+value);
}
}
//增强for方式二
@Test
public void test5() {
Map map = new LinkedHashMap();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
for (Object object : map.entrySet()) {
Map.Entry entry = (Entry) object;
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key+"="+value);
}
}
}