ConcurrentModificationException when iterating over a list

0

I skipped a ConcurrentModificationException when iterating over a list: List<Attribute> attributes This list contains objects of type Attribute , which will be used to create views AttributeView :

The method I use to create the views:

public void createAttributeViews(List<Attribute> attributes) {
        if (attributes.size() != -1) { //La lista debe contener elementos
            Iterator<Attribute> iter = attributes.iterator();
            while (iter.hasNext()) {
                Attribute attribute = iter.next();
                AttributeView view = new AttributeView(attribute);
                mainPanel.add(view.getMainPanel()); //añade la vista al panel principal
            }
        }
    }

I get the error in the line: Attribute attribute = iter.next(); all call iter.next()

The list that passed as parameter in the public void createAttributeViews(List<Attribute> attributes) method inizializzo like this:

protected void init(User user) {
    List<Attribute> userAttributes = new ArrayList<>();
    userAttributes.addAll(userAttributeService.getUserAttributesById(user.getId()));
    createAttributeViews(userAttributes);
}

Why is the error?

    
asked by Bryan Romero 01.12.2018 в 23:32
source

1 answer

0

The solution was to create another list in the class containing the method createAttributeViews () e inizializzarla with list values passed as parameters using addAll () :

public class MyClass{

private List<Attribute> attribute = new ArrayList<>();

...............

public void createAttributeViews(List<Attribute> attributes) {
this.attributes.addAll(attributes);
        if (attributes.size() != -1) { //La lista debe contener elementos
            Iterator<Attribute> iter = this.attributes.iterator();
            while (iter.hasNext()) {
                Attribute attribute = iter.next();
                AttributeView view = new AttributeView(attribute);
                mainPanel.add(view.getMainPanel()); //añade la vista al panel principal
            }
        }
    }

With the use of this other list the problem does not arise.

    
answered by 02.12.2018 / 14:35
source