Spaces:
Running
Running
| 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: | |
| [] | |
| [] | |
| =============================================== | |
| 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: | |
| [] | |
| List after: | |
| [] | |
| List before: | |
| [] | |
| List after: | |
| [] | |
| List before: | |
| [] | |
| List after: | |
| [] | |
| List before: | |
| [] | |
| List after: | |
| [] | |