增强for循环

一维数组foreach

    public static void main(String[] args){
        int[] number={10,20,30,40,50};
        //增强FOR循环,输出数组中的每一个数
        for(int x:number){
            System.out.println(x);
        }
    }

二维数组foreach

public static void main(String[] args){
        int[][] nums={{1,2,3},{4,5,6},{7,8,9}};
        for(int[] i:nums){
            for(int j:i){
                System.out.print(j);
            }
            System.out.println();
        }
    }

List使用

public static void main(String[] args) {
        List<String> arr = new ArrayList<String>();
        arr.add("你好");
        arr.add("我好");
        arr.add("大家好");

        //for循环
        for(int i=0;i<arr.size();i++){
            System.out.println(arr.get(i));    //要获取list中元素需要用get方法
        }
    }

还可以对像map这种键值对使用

public static void main(String[] args) {
        Map<String,String> mapstr = new HashMap<String,String>();
        mapstr.put("王", "男");
        mapstr.put("李", "男");
        mapstr.put("张", "女");
                            //entrySet方法是为了获取键值对的集合
        for(Map.Entry<String, String> s : mapstr.entrySet()){   //这里的Map.Entry<String, String>其实就是一个类型 用来表示键值对的类型
            System.out.println("key="+s.getKey());            //这里其实还是相当于 s=maostr.entrySet,只不过s存储的是键值对。
            System.out.println("value="+s.getValue());        //所以可以用get方法获取出来存储的键值对。
        }
    }

更多内容参考

foreach适用于只是进行集合或数组遍历,for则在较复杂的循环中效率更高。
foreach不能对数组或集合进行修改(添加删除操作),否则会报出java.util.ConcurrentModificationException异常,如果想要修改就要用for循环。

posted @ 2021-06-29 19:08  卡卡发  阅读(75)  评论(0)    收藏  举报