Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wrong values after using forEach in Arraylist

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading