最近看到 V2EX 上一个帖子《关于 Java foreach 循环删除多个元素的有趣问题(不是抛异常哦)》,我根据代码预测的执行结果与实际楼主贴出的并不相同。看了评论,才发现自己忽略了一点,觉得有点意思,因此记录一下。
帖子正文中贴出的代码为:
import java.util.ArrayList;
import java.util.List;
public class ForeachTest {
public static void main(String[] args) {
List<Integer> test = new ArrayList<>();
for (int i = 0; i < 100; i++) {
test.add(i);
}
System.out.println(test);
for (int i = 0; i < 50; i++) {
for (int t : test) {
System.out.println(t);
test.remove(t);
break;
}
}
System.out.println(test);
}
}
我预测的执行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0
1
2
3
……此处省略
47
48
49
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
实际执行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0
1
1
1
……此处省略
1
1
1
[1, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
我预测的理由是,每次最内层的循环只执行一次,并且移除第一个元素。但我忽略了一点,楼主贴出的代码之中,实际调用的是 remove(int)
方法,而不是 remove(Object)
方法。前者是根据下标移除对应元素,后者是移除对应的元素。第一次循环之中,移除了第0个元素(test.get(0)
值为0
),随后的循环,均移除第1个元素(test.get(0)
值为1
)。
因此,将 for (int t : test)
更改为 for (Integer t : test)
,即可实现预测中的输出。