Java ArrayList Remove Elements - Understanding the Output
Let's analyze the output of this Java code snippet:
List<Integer> nums = new ArrayList<>();
nums.add(0);
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
nums.add(6);
for (int i = 0; i < nums.size(); i++) {
System.out.println(nums.remove(i));
}
The output is:
0
2
4
6
Explanation:
The code iterates through the ArrayList nums using a for loop. Inside the loop, nums.remove(i) removes the element at index i and returns the removed element, which is then printed. However, the removal process changes the size and indices of the ArrayList, leading to unexpected behavior.
Here's a step-by-step breakdown:
- Iteration 1:
i = 0:nums.remove(0)removes0and prints it. The ArrayList now contains[1, 2, 3, 4, 5, 6].2. Iteration 2:i = 1:nums.remove(1)removes2and prints it. The ArrayList becomes[1, 3, 4, 5, 6]. Note that the index of3is now1due to the removal.3. Iteration 3:i = 2:nums.remove(2)removes4and prints it. The ArrayList becomes[1, 3, 5, 6].4. Iteration 4:i = 3:nums.remove(3)removes6and prints it. The ArrayList becomes[1, 3, 5]. The loop terminates becauseiis now equal tonums.size().
Key Takeaway: When removing elements from an ArrayList while iterating, be mindful that the indices shift after each removal. This can result in unexpected behavior if you're not careful.
原文地址: https://www.cveoy.top/t/topic/qg0X 著作权归作者所有。请勿转载和采集!