Iterator error (java.lang.IllegalStateException) is deleted

Code:

Iterator<StageDO> iterator = subCatalogue.getStages().iterator();
while (iterator.hasNext()) {
                        if (requestVO.getStages() != null) {
                            StageDO next = iterator.next();
                            String id = next.getId();
                            if (requestmap.get(id) != null) {
                                next.setName(requestmap.get(id).toString());
                            } else {
                                iterator.remove();
                            }
                        } else {
                            iterator.next();
                            iterator.remove();
                        }
                    }

When we use an iterative delete (Iterator.remove ()), it may be because there is no "it.next ();" this line, java.lang.IllegalStateException throw an exception, because one is not satisfied to remove the collection by Iterator when the condition of the element, first need to use the next iteration of the method elements in the collection before calling the remove method, because otherwise collection may be on the same iterator remove several times and thrown java .lang.IllegalStateException exception.

Do not forget to remember in the body of the loop iterator.next ()

Guess you like

Origin www.cnblogs.com/wuhen8866/p/11102748.html