增强for循环
格式:for(数据类型 变量名:被遍历的集合(Collection)或者数组)
{
}
- 对集合进行遍历。只能获取集合元素,但是不能对集合进行操作
- 迭代器除了遍历,还可以进行remove集合中元素的动作。
- 如果是用ListIterator,还可以在遍历中对集合进行增删改查的动作。
- 传统for循环和高级for循环有什么区别?
- 增强for循环有一个局限性,必须有被遍历的目标。
- 建议在比遍历数组的时候,还是希望使用传统for循环,因为传统for循环有角标。
import java.util.*;
public class ForEachDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> al = new ArrayList<String>();
al.add("abc1");
al.add("abc2");
al.add("abc3");
for(String s:al) {
System.out.println(s);
}
int a[] = {1,2,3};
for (int i : a) {
System.out.println(i);
}
HashMap<Integer, String> hs = new HashMap<Integer, String>();
hs.put(1, "a");
hs.put(2, "b");
hs.put(3, "c");
Set<Integer> keySet = hs.keySet();
for(Integer i: keySet) {
System.out.println(i+"---"+hs.get(i));
}
Set<Map.Entry<Integer, String>> entrySet = hs.entrySet();
for(Map.Entry<Integer, String> me:entrySet) {
System.out.println(me.getKey()+"---"+me.getValue());
}
// for(Map.Entry<Integer, String> me: hs.entrySet()) {
// System.out.println(me.getKey()+"---"+me.getValue());
// }
}
}