Java17-foreach循环遍历

for each语法格式:

for(数据类型 每次循环的元素名称: 循环对象){
}

for each 遍历数组:

package com.clover.demo;

import java.text.SimpleDateFormat;
import java.util.Date;

public class test_foreach {
    public static void main(String[] args) {

        int[] arr = { 11, 22, 55, 66, 99, 88 };
        long a = System.currentTimeMillis();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd   HH:mm:ss");

        Date date = new Date(a);
        System.out.println("开始时间:" + formatter.format(date));
        for (int i : arr) {
            System.out.println(i);
        }
        long b = System.currentTimeMillis();
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy:MM:dd   HH:mm:ss");

        Date date1 = new Date(b);
        System.out.println("结束时间:" + formatter1.format(date));


    }

}

 

 


for each 遍历集合:

package com.clover.demo;

import java.util.ArrayList;

public class test_foreach01 {
    public static void main(String[] args) {
        System.out.println("-----------示例一--------");
        // 集合演示
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");

        for (String s : list) {
            System.out.println(s);
        }

        System.out.println("-----------示例二--------");
        ArrayList<test_student> list1 = new ArrayList<>();
        list1.add(new test_student("一一", 13));
        list1.add(new test_student("二二", 34));
        list1.add(new test_student("三三", 25));
        list1.add(new test_student("四四", 26));
        list1.add(new test_student("五五", 37));

        for (test_student s : list1) {
            System.out.println(s.getName() + "..." + s.getAge());
        }
    }

}

 

test_student 类:

public class test_student {
    public String name;
    public int age;
    public String sex;
    
    //有參構造方法
    public test_student(String name,int age,String sex){
        this.name=name;
        this.age=age;
        this.sex=sex;
    }
    

    public test_student(String name, int age) {
        // TODO Auto-generated constructor stub
        this.name=name;
        this.age=age;
    
     //省略 get和set方法
    }
}

 

阿里巴巴开发规范:

 

posted @ 2020-09-02 10:36  eosclover  Views(1777)  Comments(0Edit  收藏  举报