adey1
adey1

Reputation: 31

How to fix ConcurrentModificationException error when adding items during iteration

So I am getting a "java.util.ConcurrentModificationException at java.util.ArrayList$Itr.next(ArrayList.java:860)" error.

I know the reason I am getting this error is because I am iterating over a list at the same time that I am adding objects to that list. However, I do not know how to add a listIterator to fix this problem.

If someone could show me how to add the iterator, that would be amazing. Thank you!

I have indicated where the error starts in my code

//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) {

        }
    });
}

Upvotes: 1

Views: 2067

Answers (1)

Vladimir Zakharov
Vladimir Zakharov

Reputation: 36

ListIterator has the add method, you can use it like this:

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

But to add a user only if it doesn't exist in the list you don't need an iterator. If you do it inside of the loop, you will add a user for each of the list's users that doesn't have the same id. But instead you need to check that the user's id is dirrenet from all users' ids and add the user only once. If you are using Java 8, you could do something like this:

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

Upvotes: 2

Related Questions