0

What is the out put of this code? In the description

ArrayList<Long> table = new ArrayList<>(); int position = 1; table.add(10); table.add(5); table.add(position, 15); table.remove(2); for (Integer i: table){     sum += i; } System.out.println(sum); Confused by this but it was on a test and not explained

15th Nov 2019, 8:12 AM
Catie Hyman
Catie Hyman - avatar
2 ответов
+ 3
the output should be 25. don't forget that indexes start from zero. 10 is added to the first index 0 5 is added to the second index 1 then 15 is added to position = 1 and that replaces 5. so the list now has {10,15} then remove the 2 index, it doesn't exit only index 0 = 10 and index 1 = 15 exit, so nothing happens. in the for loop all the elements are summed so 10 + 15 = 25
15th Nov 2019, 9:21 AM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
here's the correct code by the way : import java.util.*; public class Program { public static void main(String[] args) { int sum =0; ArrayList<Integer> table = new ArrayList<>(); int position = 1; table.add(10); table.add(5); table.add(position, 15); table.remove(2); for (Integer i: table){ sum += i; } System.out.println(sum); } }
15th Nov 2019, 9:22 AM
Bahhaⵣ
Bahhaⵣ - avatar