Question

I am trying to iterate custom object using iterator and adding data into that custom object but when size of object is 1 it's working but when I am adding second data it gives me an error : nested exception is java.util.ConcurrentModificationException

My Code is as Follow :

public List<ValidationObject> _validationObjects = new ArrayList<>();

    public void addError(String key, String value){
        int size = _validationObjects.size();
        if(size==0){
            ValidationObject vo = new ValidationObject();
            vo.setKey(key);
            vo.addLine(value);
            _validationObjects.add(vo);
        }
        else{
            Iterator i = _validationObjects.iterator();
            while(i.hasNext()){
                ValidationObject obj = (ValidationObject)i.next();
                if(obj.getKey().equals(key)){
                    obj.addLine(value);
                }else{
                    ValidationObject vo = new ValidationObject();
                    vo.setKey(key);
                    vo.addLine(value);
                    _validationObjects.add(vo);
                }
            }
        }
    }

In class ValidatioObject I have variable as follow :

private List<String> _lines;
private String _key;

I am calling addError() method as follow :

list.addError("Name", "Should not empty");
list.addError("Prefix", "Should not empty");

Any Help on it, why it's behaving like this.

Was it helpful?

Solution

I think you need to change the logic. Add to your list outside the iterator

else{
                boolean keyFound = false;
                Iterator i = _validationObjects.iterator();
                while(i.hasNext()){
                    ValidationObject obj = (ValidationObject)i.next();
                    if(obj.getKey().equals(key)){
                        obj.addLine(value);
                        keyFound = true;
                    }
                }
                if(!keyFound){
                        ValidationObject vo = new ValidationObject();
                        vo.setKey(key);
                        vo.addLine(value);
                        _validationObjects.add(vo);
                }
            }

OTHER TIPS

Why this exception is because of this line,

_validationObjects.add(vo);

beacuse,

If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

So try adding that using the iterator instance only.

Define a ListIterator and add to that,

ListIterator i=_validationObjects.listIterator();
i.add(vo);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top