那天,小二去阿里面试,面试官老王一上来就甩给了他一道面试题:为什么阿里的 Java 开发手册里会强制不要在 foreach 里进行元素的删除操作?小二听完就面露喜色,因为两年前,也就是 2021 年,他在《Java 程序员进阶之路》专栏上的第 63 篇看到过这题😆。
PS:star 这种事,只能求,不求没效果,铁子们,《Java 程序员进阶之路》在 GitHub 上已经收获了 523 枚星标,小伙伴们赶紧去点点了,冲 600 star!
为了镇楼,先搬一段英文来解释一下 fail-fast。
In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system’s state at several points in an operation, so any fa
阿里Java开发手册建议不要在foreach循环中执行删除操作,这是因为fail-fast机制。该机制在检测到集合状态改变时立即抛出异常。foreach循环底层使用Iterator,当删除元素时引发ConcurrentModificationException。正确删除元素的方法包括使用Iterator的remove方法,或者避免使用break。了解fail-fast可以帮助避免不必要的错误。
订阅专栏 解锁全文
9848

被折叠的 条评论
为什么被折叠?



