-1

I try to run this sample program but fail in the console and pop up -

Exception in thread "main" java.util.ConcurrentModificationException

What it purpose is create arraylist, add some string then delete string start with "A" in the arraylist.

here is code:

    List<String> dryFruits = new ArrayList<();
          dryFruits.add("Walnut");
          dryFruits.add("Apricot");
          dryFruits.add("Almond");
          dryFruits.add("Date");
    Iterator<String> iterator = dryFruits.iterator();
    while(iterator.hasNext()) {
        String dryFruit = iterator.next();
        if(dryFruit.startsWith("A")) {
            dryFruits.remove(dryFruit);
        }
    }
    System.out.println(dryFruits);

I expecting print out [Walnut, Date] only.

Don
  • 9

1 Answers1

-2

Exception said that: This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. You changed contains of iterated List, I can suggest as follow resolve:

List<String> dryFruits = new ArrayList<>();
        List<String> result = new ArrayList<>();
        dryFruits.add("Walnut");
        dryFruits.add("Apricot");
        dryFruits.add("Almond");
        dryFruits.add("Date");
        Iterator<String> iterator = dryFruits.iterator();
        while(iterator.hasNext()) {
            String dryFruit = iterator.next();
            if(!dryFruit.startsWith("A")) {
                result.add(dryFruit);
            }
        }
        System.out.println(result);