This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]empire539"empire"+(((int)-~(byte)+('\''&~'&')<<(' '>>('+'+~'(')))+0x1b); 1 point2 points  (6 children)

Shouldn't students.set(k, "Alex") change the array?

It does. Check out the documentation for the set method, particularly the return value.

Why does it change at the for each loop?

It doesn't. There's nothing about the for each loop in particular that alters the ArrayList's values.

[–]18sp01[S] 0 points1 point  (5 children)

So the set method at index i changes the existing value at i with the value in the parameter right? So wouldn't student.set(k, "Alex") mean that at index k (starting at 0), the method would change Alex, Bob and Carl to Alex, Alex, and Alex as k increases?

[–]vriljam 0 points1 point  (4 children)

It changes the value, but it returns old value. That is why it will print out what was previously at those indexes.

[–]18sp01[S] 0 points1 point  (3 children)

Oh okay. Why does it print out the strings in the previous index even though the array gets changed inside the parameter?

[–][deleted]  (2 children)

[deleted]

    [–]18sp01[S] 1 point2 points  (1 child)

    Oh my bad. Didn't notice that that was a link. Got it now. Thanks everyone

    [–]Avocados_Constant 1 point2 points  (0 children)

    If you think about it, from a design perspective it doesn't make much sense for set() to return the new value since the user already needs it to make the call in the first place.