foreach java循环能够修改集合集合吗?

时间:2016-09-19 07:45:19

标签: java

我有一个 set 集合,我想只读以便比较值,问题是我得到了一个 java.util.ConcurrentModificationException ,但我没有更改设置元素。

            Set<eu.datex2.schema._2_0._2_3.SituationRecord> setSituation = map.keySet();

            for (SituationRecord situationRecord : situationRecordList) {
                String implementedSituationTRecordClass = situationRecord.getClass().toString().substring(32);
                synchronized (setSituation) {
                    //The problem is in the next line
                    for (eu.datex2.schema._2_0._2_3.SituationRecord situ : setSituation) {
                        if (Objects.equals(situ.getId(), situationRecord.getId())) {//Comparamos si ya existe en el mapa
                            System.out.println("ID from map: " + situ.getId() + "ID from datex1: " + situationRecord.getId());
                            situationRecordList2.add(situ);
                            flagSituatinNoEncontrado.setValor(false);
                        }
                        if (flagSituatinNoEncontrado.isValor()) {
                            System.out.println("CREA");
                            situationRecordList2 = giveMeAsituationRecord2List(situationRecordList2, implementedSituationTRecordClass, situationRecord, global, uniqe, map, latitude, longitude, delta, areaAdministracion, numCarretera);
                        }
                    }
                }

            }

        }

1 个答案:

答案 0 :(得分:0)

我已经修复了迭代列表而不是集合的问题,但我仍然不明白为什么你不能迭代一组抽象类。

Set<eu.datex2.schema._2_0._2_3.SituationRecord> setSituation = Collections.synchronizedSet(map.keySet());
List<eu.datex2.schema._2_0._2_3.SituationRecord> list = Collections.synchronizedList(new LinkedList<>());
list.addAll(setSituation);