高级for循环

格式:
for(数据类型 变量名:被遍历的集合(Collection)或者数组){
}
对集合进行遍历,只能获取元素 但不能对集合进行操作

import java.util.*;
class Test{
    public static void main(String[] args){
        ArrayList<String> al1=new ArrayList<>();
        al1.add("abc1");
        al1.add("abc2");
        al1.add("abc3");
        /*
        Iterator<String> it=al1.iterator();
        while (it.hasNext()){
            sop(it.next());
        }
        */
        for (String s:al1){//底层原理还是迭代器,简化书写
            sop(s);
        }
        HashMap<Integer,String> hm=new HashMap<>();
        hm.put(1,"a");
        hm.put(2,"b");
        hm.put(3,"c");
        //Set<Map.Entry<Integer,String>> entrySet1=hm.entrySet();
      //for(Map.Entry<Integer,String> me:entrySet1){}
        for(Map.Entry<Integer,String> me:hm.entrySet()){
            sop(me.getKey()+"---"+me.getValue());
        }
    }
    public static void sop(Object obj){
        System.out.println(obj);
    }
}

 

传统for循环和高级for有什么区别呢?
高级for循环有一个局限性 必须有被遍历的目标
建议在遍历数组的时候,还是希望使用传统for,因为传统for可以定义角表

 

posted @ 2015-12-27 17:32  唱一些温暖  阅读(195)  评论(0编辑  收藏  举报