suba
suba

Reputation: 33

What will happen if the conditon in the for loop is continuously changed?

What will be the result of the following block of code?

 ArrayList<Integer> myList = new ArrayList<Integer>();
   for (int i = 0; i < myList.size(); i++) {
   myList.remove(i);
    }

The answer is provided as the loop will never run.

But for an input of [-1, 3, 28, 17, 9, 33], I got [3, 17, 33] as output. What does it mean?

Upvotes: 1

Views: 85

Answers (2)

Taslim Oseni
Taslim Oseni

Reputation: 6263

Wrong! The loop will run as long as the conditions are still satisfied. Every iteration will produce a new scenario and the conditions just bend around to suit the new values.

Using your example [-1, 3, 28, 17, 9, 33]:

  • First iteration: i is 0... 0 is less than 6.. element at index 0 (-1) is hence removed

    Resultant arrraylist: [3, 28, 17, 9, 33]

  • Second iteration: i is 1... 1 is less than 5.. element at index 1 (28) is hence removed

    Resultant arrraylist: [3, 17, 9, 33]

  • Third iteration: i is 2... 2 is less than 4.. element at index 2 (9) is hence removed

    Resultant arrraylist: [3, 17, 33]

  • Fourth iteration: i is 3... 3 is not less than 3.. Iteration stops.

After the loop operation, your MyList arraylist will be reduced to:

[3, 17, 33]

I hope this helps, merry coding!

Upvotes: 1

Janar
Janar

Reputation: 2701

The condition is evaluated on each iteration. At the beginning the list contains [-1, 3, 28, 17, 9, 33] and the loop begins:

  • i = 0; 0 < 6 is true, current list [-1, 3, 28, 17, 9, 33], element with index 0 (bolded) removed, remaining [3, 28, 17, 9, 33]
  • i = 1; 1 < 5 is true, current list [3, 28, 17, 9, 33], element with index 1 (bolded) removed, remaining [3, 17, 9, 33]
  • i = 2; 2 < 4 is true, current list [3, 17, 9, 33], element with index 2 (bolded) removed, remaining [3, 17, 33]
  • i = 3; 3 < 3 is false, loop ends, remains [3, 17, 33]

Upvotes: 6

Related Questions