Requirement: I have a collection, as follows, I want to determine whether there is a "world" element in it, if there is, I add a "javaee" element, please write code implementation.
The code is as follows:
- public class Test {
- public static void main(String[] args) {
- List<String> list = new ArrayList<String>();
- list.add("java");
- list.add("world");
- list.add("android");
- Iterator<String> iterator = list.iterator();
- while(iterator.hasNext()){
- String content = iterator.next();
- if("world".equals(content)){
- list.add("hello");
- }
- }
- System.out.println(list);
- }
- }
Running error message:
First, we open the jdk document to see the exception, because java is an object-oriented language and the exception is encapsulated as an object.
Concurrent ModificationException: This exception is thrown when a method detects concurrent modifications to an object but does not allow such modifications.
Reasons for this:
Iterators depend on sets. After judging success, new elements are added to the set, but the iterator does not know, so it makes an error, which is called concurrent modification exception.
In fact, this problem describes that when iterators traverse elements, elements cannot be modified through collections.
How to solve it?
A: Iterator iteration elements, iterator modification elements
The element follows the element just iterated.
B: Set traversal elements, set modification elements (ordinary for)
Elements are added at the end
Solution: for loop I will not try to solve it in another way, the code is as follows:
- public class Test {
- public static void main(String[] args) {
- List<String> list = new ArrayList<String>();
- list.add("java");
- list.add("world");
- list.add("android");
- ListIterator lit = list.listIterator();
- while (lit.hasNext()) {
- String s = (String) lit.next();
- if ("world".equals(s)) {
- lit.add("javaee");
- }
- }
- System.out.println(list);
- }
- }
Because ListIterator has the add() method, it solves the problem.