Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

枚举那片文章的EnumMap的groupPizzaByStatus方法有问题 #900

Closed
kekeboomboom opened this issue Aug 18, 2020 · 0 comments
Closed

枚举那片文章的EnumMap的groupPizzaByStatus方法有问题 #900

kekeboomboom opened this issue Aug 18, 2020 · 0 comments
Labels
bug

Comments

@kekeboomboom
Copy link

@kekeboomboom kekeboomboom commented Aug 18, 2020

文章地址

public static EnumMap<PizzaStatus, List<Pizza>> 
  groupPizzaByStatus(List<Pizza> pizzaList) {
    EnumMap<PizzaStatus, List<Pizza>> pzByStatus = 
      new EnumMap<PizzaStatus, List<Pizza>>(PizzaStatus.class);

    for (Pizza pz : pizzaList) {
        PizzaStatus status = pz.getStatus();
        if (pzByStatus.containsKey(status)) {
            pzByStatus.get(status).add(pz);
        } else {
            List<Pizza> newPzList = new ArrayList<Pizza>();
            newPzList.add(pz);
            pzByStatus.put(status, newPzList);
        }
    }
    return pzByStatus;
}

方法中对pizzaList在for循环中进行add操作,导致ConcurrentModificationException。

将for循环部分代码,替换成如下代码:

        Iterator<Pizza> iterator = pizzaList.iterator();
        while (iterator.hasNext()) {
            Pizza pz = iterator.next();
            PizzaStatus status = pz.getStatus();
            if (pzByStatus.containsKey(status)) {
                pzByStatus.get(status).add(pz);
            } else {
                List<Pizza> newPzList = new ArrayList<>();
                newPzList.add(pz);
                pzByStatus.put(status, newPzList);
            }
        }
@Snailclimb Snailclimb added the bug label Aug 23, 2020
@Snailclimb Snailclimb closed this Aug 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants