Skip to content

Activity 8: ArrayList Objects

Instructions

Example Code

Model 1

 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
import java.util.ArrayList;

public class Model1 {

    public static void main(String[] args) {
        example1();
        example2();
    }

    public static void example1() {
        int[] nums;
        nums = new int[3];

        nums[0] = 74;
        nums[1] = 11;
        nums[2] = 21;

        System.out.println(nums.length);
        System.out.println(nums);
    }

    public static void example2() {
        ArrayList<Integer> nums;
        nums = new ArrayList<Integer>();

        nums.add(74);
        nums.add(11);
        nums.add(21);

        System.out.println(nums.size());
        System.out.println(nums);
    }

}

Model 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import java.util.ArrayList;

public class Model2 {

    public static void main(String[] args) {
        ArrayList<Integer> nums;
        nums = new ArrayList<Integer>();
        for (int i = 0; i < 1000; i++) {
            nums.add(i);
        }
        System.out.println("Size = " + nums.size());
        System.out.println("Data = " + nums);
    }

}

Model 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.util.Arrays;

public class Model3 {

    public static void main(String[] args) {
        final int N = 4;
        int[] nums = new int[N];
        for (int i = 0; i < N; i++) {
            nums[i] = i + 1;
        }
        for (int i = 0; i < N; i++) {
            nums[i] *= 5;
        }
        System.out.println(Arrays.toString(nums));
    }

}