File size: 2,152 Bytes
fe7cdd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
Write the method

void addSum(ArrayList<Integer> numbers) 

...which calculates the sum of the numbers in the list and adds it as the last element of the list.


Example method call:
public static void main(String[] parameters){
    ArrayList<Integer> numbers = new ArrayList<>();
    for (int i=1; i<5; i++) {
        numbers.add(i);
    }
    System.out.println(numbers);
    addSum(numbers);
    System.out.println(numbers);
}

Program outputs:
[1, 2, 3, 4]
[1, 2, 3, 4, 10]
 
 
===============================================
 
import java.util.Random;
import java.util.ArrayList;

public class Test{
    public static void main(String[] args){
        final Random r = new Random();
        
        int[][] s = {{1,2,3}, {10,20,30,40}, {2,4,6,8,10}, {9,1,8,2,7,3,6,4}};
        
        for (int[] pa : s) {

            // if we do not recreate a new list
            // then go through each element to add then to our new list
            // we get the references
            // [I@29ba4338
            // [I@57175e74
            // [I@7bb58ca3
            // [I@c540f5a
            ArrayList<Integer> lista = new ArrayList<>();
            for (int l : pa) lista.add(l);
            // vs recreating a new list for each sub-list
            // [1, 2, 3]
            // [10, 20, 30, 40]
            // [2, 4, 6, 8, 10]
            // [9, 1, 8, 2, 7, 3, 6, 4]
            
            
            System.out.println("List before: ");
            System.out.println("" + lista);
            System.out.println("List after: ");
            addSum(lista);
            System.out.println(lista);
        }
    }


    //ADD
    // dont return anything
    // cuz we update the list inplace
    public static void addSum(ArrayList<Integer> numbers) {
        int sum = 0;
        for (int i : numbers) {
            sum += i;
        }
        numbers.add(sum);
    }




}









List before: 
[1, 2, 3]
List after: 
[1, 2, 3, 6]
List before: 
[10, 20, 30, 40]
List after: 
[10, 20, 30, 40, 100]
List before: 
[2, 4, 6, 8, 10]
List after: 
[2, 4, 6, 8, 10, 30]
List before: 
[9, 1, 8, 2, 7, 3, 6, 4]
List after: 
[9, 1, 8, 2, 7, 3, 6, 4, 40]