java 高级for循环

/*
高级for循环是集合中(Collection)迭代器的简写形式。即集合中的迭代器可以使用高级for来代替。
格式:
for(数据类型 变量名:被便利的集合(Collection)或数组)
{

}

高级for循环只对集合进行遍历。
只能获取集合元素,但是不能对集合进行操作。

迭代器除了遍历,还可以进行remove集合中元素的动作。
如果使用ListIterator,还可以对集合中的元素进行增删改查的动作。


传统for循环和高级for循环有什么区别呢?
高级for循环有一个局限性,必须有被遍历的目标;
建议在遍历数组的时候还是使用传统for。因为传统for可以定义角标。
*/
import java.util.*;
class ForEachDemo 
{
	public static void main(String[] args) 
	{
		/*
		ArrayList<String> al=new ArrayList<String>();
		al.add("abc1");
		al.add("abc2");
		al.add("abc3");
		for(String s:al)
			sop(s);

		int[] arr={1,3,4,5,2};
		for(int i:arr)
			sop("i:"+i);
		*/
		HashMap<Integer,String> hm=new HashMap<Integer,String>();
		hm.put(1,"hello1");
		hm.put(3,"hello3");
		hm.put(2,"hello2");
		hm.put(4,"hello4");

		Set<Integer> set=hm.keySet();
		for(Integer i:set)
			sop(i+".."+hm.get(i));


		Set<Map.Entry<Integer,String>> set1=hm.entrySet();
		for(Map.Entry<Integer,String> me:set1)
		{
			Integer key=me.getKey();
			String value=me.getValue();
			sop(key+"......."+value);
		}

	}


	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值