0

I want that after writing any message, the user gets into the list. The first time it works, but as soon as another user writes, for some reason it shows null.

@Override
public void onUpdateReceived(Update update) {
    if (update.hasMessage() && update.getMessage().hasText()) {
        getLogs(update);
        addUser(update.getMessage().getChat().getUserName(), update.getMessage().getChatId());
    }
}

private void addUser(String name, long chatId) {
    Buddy buddy;
    if (!users.isEmpty()) {
        for (Buddy user : users) {
            if (name.equals(user.getName()) && chatId == user.getNameId()) {
                System.out.println("Exists");
            } else {
                buddy = new Buddy(name, chatId);
                users.add(buddy);
            }
        }
    } else {
        users.add(new Buddy(name, chatId));
    }
    System.out.println(users.toString());
}

I expected that after writing from any user, a unique Buddy would be added to the list, but for some reason this did not happen.

Catching such a mistake: java.util.ConcurrentModificationException: null

1
  • Off topic, you are adding a new Buddy for each existing item in users. Commented Feb 12, 2023 at 22:25

1 Answer 1

1

You are iterating through users:

for (Buddy user : users) {

while changing the users list:

buddy = new Buddy(name, chatId);
users.add(buddy);

== ConcurrentModificationException

You have to add the user, if not found, after you have finished the for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

The alternative is to explicitly use the list iterator and add it through the list iterator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.