I`m doing the freecodecamp beginner tutorial and I have a problem with forEach function in Arraylist. Following Code
number1.forEach(number -> {
number1.set(number1.indexOf(number), number * 2);
});
System.out.println(number1);
The values are [2, 4, 11, 12] so I would expect to get [4, 8, 22, 24] but instead I get [8, 4, 22, 24]
Any Ideas what`s wrong?
As stated above. I tried to check with indexOf if the values and indexes aren`t switched, because I used Sort function earlier, but they seem to be ok. Other than that, everything went smooth and easy. IDK
CodePudding user response:
You start with [2, 4, 11, 12]
During the first iteration, number = 2
You then call number1.set(number1.indexOf(2), 2 * 2)
We now have [4, 4, 11, 12]
During the second iteration, number = 4
Once again, we call number1.set(number1.indexOf(4), 4 * 2)
Here is the problem: indexOf returns the index of the first instance of that value!
So, number1.indexOf(4) = 0
, so it places 8
into index 0
instead of index 1
As @Tibrogargan mentioned in the comments, this is a prime example of why you shouldn't modify an array while iterating across it
Your code for number1
will not work whenever there exists a number Y
in number1
such that there exists a number X
where Y = 2X