更多面试资料同步整理在github:TrustInCS
本文同步github
简单的一个ArrayList案例
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
for (String s : list){
if ("1".equals(s)){
list.remove(s);
}
}
}
- 代码会正常执行吗?
- 不会,那会导致什么?
- 数组越界?
直接执行一下:
Connected to the target VM, address: '127.0.0.1:64296', transport: 'socket'
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.demo.demo.DemoApplicationTests.main(DemoApplicationTests.java:369)
介绍一下这个异常:
ConcurrentModificationException 并发修改异常
* This exception may be thrown by methods that have detected concurrent
* modification of an object when such modification is not permissible.
* <p>
* For example, it is not generally permissible for one thread to modify a Collection
* while another thread is iterating over it. In general, the results of the
* iteration are undefined under these circumstances. Some Iterator
* implementations (including those of all the general purpose collection implementations
* provided by the JRE) may choose to throw this exception if this behavior is
*