在迭代期间添加项目时如何修复 ConcurrentModificationException 错误

How to fix ConcurrentModificationException error when adding items during iteration

所以我收到 "java.util.ConcurrentModificationException at java.util.ArrayList$Itr.next(ArrayList.java:860)" 错误。

我知道我收到此错误的原因是因为我在将对象添加到该列表的同时遍历列表。但是,我不知道如何添加 listIterator 来解决这个问题。

如果有人能告诉我如何添加迭代器,那就太棒了。谢谢!

我已经在我的代码中指出了错误开始的地方

//method to evaluate who you have chatted with and display on screen
private void readChats() {
    users = new ArrayList<>();

    reference = FirebaseDatabase.getInstance().getReference("USERS");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            users.clear();


            //gets every user snapshot from "USERS" children in firebase and make User obj
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                User user = snapshot.getValue(User.class);

                //for every ID that was stored in textTransacRec list
                for (String ID : textTransacRec) {
                    //out of all existing users in firebase if a user's ID matches any of the ID's in textTransacRec
                    if(user.getID().equals(ID)) {
                        //if there are any User objects inside users list
                        if(users.size() != 0) {
                            //check to see if the user already exists in list or not by matching w/ existing user ID's
                            //if there is no ID match then user does not exist --> add to users list to display
                            //---------------------------ERROR STARTS FROM HERE----------------------
                            for(User u : users) {
                                if(!user.getID().equals(u.getID())) {
                                    users.add(user);
                                }
                            }
                        }
                        //if no User objects inside users list --> add to users list
                        else {
                            users.add(user);
                        }
                    }
                }
            }
            chatRecyclerAdap = new ChatRecyclerAdap(getContext(), users);
            recyclerView.setAdapter(chatRecyclerAdap);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

ListIterator 有 add 方法,你可以这样使用它:

ListIterator<User> iterator = users.listIterator();
while(iterator.hasNext()) {
    User u = iterator.next();
    if(!user.getID().equals(u.getID())) {
        iterator.add(user);
    }
}

但是仅当列表中不存在用户时才添加用户不需要迭代器。如果您在循环内执行此操作,您将为每个没有相同 ID 的列表用户添加一个用户。但是相反,您需要检查用户的 ID 是否是来自所有用户 ID 的 dirrenet,并且只添加一次用户。 如果你使用的是 Java 8,你可以这样做:

    boolean userExists = users.stream().filter(u -> u.getID().equals(user.getID())).findFirst().isPresent();
    if (!userExists) {
        users.add(user);
    }