增强for循环是jdk1.5出现的新特性,作用是简化迭代器的书写格式(增强for循环的底层还是使用了迭代器遍历)。
适用范围:
实现了Iterable接口的对象或者是数组对象都可以使用增强for循环。
格式:
for(数据类型 变量名 : 被遍历的集合(Collection)或者数组)
{
}
和迭代器以及传统for循环对比:
1..增强for循环对集合进行遍历时只能获取集合元素,但是不能对集合进行操作。
迭代器除了遍历,还可以进行remove集合中元素的动作。如果是用ListIterator,还可以在遍历过程中对集合进行增删改查的动作。
2..普通for循环可以没有遍历的目标,而增强for循环一定要有遍历的目标
建议在遍历数组的时候,还是使用传统for,因为传统for可以定义脚标。
import java.util.*;
public class ForeachDemo {
public static void main(String[] args) {
//1..遍历数组
int[] arr = {6,3,1,5,8};
for(int a : arr)
{
System.out.println(a);
}
//2..遍历List
List<String> lt = new ArrayList<String>();
lt.add("zhangsan");
lt.add("lisi");
lt.add("wangwu");
for(String l:lt)
{
System.out.println(l);
}
//3..遍历Set
Set<String> hs = new HashSet<String>();
hs.add("zhaoliu");
hs.add("liba");
hs.add("zhoujiu");
for(String h:hs)
{
System.out.println(h);
}
//4..遍历map()
//Map集合没有实现Iterable接口,所以map集合不能直接使用增强for循环,还是需要借助于Collection集合
Map<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1, "yy1");
hm.put(2, "tt1");
hm.put(3, "uu1");
/*for(Integer i : hm.keySet())
{
System.out.println(i+":"+hm.get(i));
}*/
for(Map.Entry<Integer,String> me : hm.entrySet())
{
System.out.println(me.getKey()+"------"+me.getValue());
}
}
}