简单的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)
        {
            System.out.println(s);
        }

        int []arr = {1,4,6};
        for(int x=0;x<arr.length;x++)
        {
            System.out.println(arr[x]);
        }

        for(int i:arr)
        {
            System.out.print(i);
        }
        /*
        Iterator<String>it = al.iterator();
        while(it.hasNext())
        {
            sop(it.next());
        }
        */

        HashMap<Integer,String>hm = new HashMap<Integer,String>();
        hm.put(1,"a");
        hm.put(2,"b");
        hm.put(3,"c");

        //第一种方式
        System.out.println(" ");
        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());
        }

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

结果: 
abc1 
abc2 
abc3 



146 
1::a 
2::b 
3::c 
1——a 
2——b 
3——c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值