Reputation: 33
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
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
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:
Upvotes: 6