Java ArrayList and loops

import java.util.ArrayList;
import java.util.Arrays;

class Whatever {
    public static void main(String[] args) {
        ArrayList<Integer> x = new ArrayList<>();
        x.add(1);

        ArrayList<Integer> y = new ArrayList<>(Arrays.asList(1,2,3));
        y.add(4);
        y.add(0, 0);
        System.out.println(x);
        System.out.println("Size: "+y.size());

        System.out.println("Shortest approach");
        y.forEach(System.out::println);

        System.out.println("Slightly longer approach");
        y.forEach(z -> System.out.println(z));

        System.out.println("Even Slightly longer approach");
        y.forEach(z -> {
            System.out.println("z: "+z);
        } );

        System.out.println("for (Integer z: y)");
        for (Integer z: y) {
            System.out.println("z: "+z);
        }

        System.out.println("Older approach");
        for (int i=0; i<y.size(); i++) {
            System.out.println(y.get(i));
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *