JAVA-增强for循环

JAVA-增强for循环

世界上只有一种英雄主义,那就是了解生命而且热爱生命的人。——罗曼·罗兰

增强for循环综述

格式:
for(数据类型 变量名 : 被遍历的集合(Collection)或者数组)
{
    }
对集合进行遍历。
只能获取集合元素。但是不能对集合进行操作。
迭代器除了遍历,还可以进行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)
        {
            //s = "kk";
            System.out.println(s);
        }

        System.out.println(al);
        /*
        Iterator<String> it = al.iterator();

        while(it.hasNext())
        {
            System.out.println(it.next());
        }
        */

        int[] arr = {3,5,1};

        for(int x=0; x<arr.length; x++)
        {
            System.out.println(arr[x]);
        }
        for(int i : arr)
        {
            System.out.println("i:"+i);
        }


        HashMap<Integer,String> hm = new HashMap<Integer,String>();

        hm.put(1,"a");
        hm.put(2,"b");
        hm.put(3,"c");

        Set<Integer> keySet = hm.keySet();
        for(Integer i : keySet)
        {
            System.out.println(i+"::"+hm.get(i));
        }

//      Set<Map.Entry<Integer,String>> entrySet = hm.entrySet();
//      for(Map.Entry<Integer,String> me : entrySet)

        for(Map.Entry<Integer,String> me : hm.entrySet())
        {
            System.out.println(me.getKey()+"------"+me.getValue());
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值