TurkuBasicOOPinJava / Week 3: Objects, files and exceptions /3b. Add sum to list - RECREATE LIST
KaiquanMah's picture
ArrayList<Integer> lista = new ArrayList<>(); for (int l : pa) lista.add(l);
fe7cdd6 verified
raw
history blame
2.15 kB
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]