增强for循环

增强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());
//		}
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值