迭代时添加元素

adding elements while iterating

我有一个具体对象的列表。在遍历此列表时,我试图通过添加值来更新它的对象,当然我得到了一个 ConcurentModificationException: 我有什么选择?谢谢并感谢您的帮助。我正在使用 Java 11.

import lombok.Data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class Test {

    public static void main(String[] args) throws IOException {

        List<Person> myList = new ArrayList<>();
        List<Hobby> hobbies = new ArrayList<>();
        Hobby h1 = new Hobby("SKI");
        Hobby h2 = new Hobby("reading");
        hobbies.add(h1);
        hobbies.add(h2);
        Person p = new Person("R", hobbies);

        Person p1 = new Person("M", hobbies);

        myList.add(p);
        myList.add(p1);
        myList
                .forEach(currentElement -> {
                    if (Objects.isNull(currentElement.getHobbies())) {
                        currentElement.setHobbies(Collections.singletonList(new Hobby("NOTHING")));

                    } else {
                        currentElement.getHobbies()
                                .forEach(hobby -> {
                                    if (hobby.getMyHobby().equals("SKI")) {
                                        currentElement.getHobbies().add(new Hobby("SAILING"));
                                    } else {
                                        hobby.getMyHobby().toLowerCase();
                                    }
                                });
                    }
                });
    }

    @Data
    static
    class Person {
        String name;
        List<Hobby> hobbies;

        public Person(String name, List<Hobby> hobbies) {
            this.name = name;
            this.hobbies = hobbies;
        }
    }

    @Data
    static class Hobby {
        String myHobby;

        public Hobby(String myHobby) {
            this.myHobby = myHobby;
        }
    }
}

您可以改为遍历索引:

for (int i = 0; i < currentElement.getHobbies().size(); i++) {
    Hobby hobby = currentElement.getHobbies().get(i);
    if (hobby.getMyHobby().equals("SKI")) {
        currentElement.getHobbies().add(new Hobby("SAILING"));
    } else {
        hobby.getMyHobby().toLowerCase();  // sic
    }
}