Question

I am learning stacks and find them pretty amusing, however, my iteration through my user-defined stack is ouputting the following:

Also, the goal of the program is to have user enter the data until "end" is entered and then print the stack from top to bottom.

Error


insertionException in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Vector.java:1156)
at java.util.Vector$Itr.next(Vector.java:1133)
at Stacker.main(Stacker.java:29)

Program


import java.util.*;

public class Stacker {

    public static void main(String[]args)
    {
        Scanner input = new Scanner(System.in);
        Stack<String> stackInformation = new Stack<String>();
        Iterator<String> iter = stackInformation.iterator();

        String stackAdd = input.nextLine();

        while (!stackAdd.equalsIgnoreCase("end"))
        {
            stackInformation.push(stackAdd);

            stackAdd = input.nextLine();

        }

        System.out.println("Exited stack insertion");

        while(iter.hasNext() && iter.next()!=null)
        {
            System.out.println(iter.next());
        }

    }

}
Was it helpful?

Solution

You've modified the stack by adding elements in the collection after you get the iterator, that's why you got this error.

You need to call the iterator once you finished to add all the elements into the stack.

Iterator<String> iter = stackInformation.iterator();
System.out.println("Exited stack insertion");

while(iter.hasNext()){
    System.out.println(iter.next());
}

Note that you can also use the for-each loop:

System.out.println("Exited stack insertion");
for(String s : stackInformation){
    System.out.println(s);
}

OTHER TIPS

In your code, you are first creating an iterator, than modifying the stack. An iterator checks for any changes and returns an error if the collection has been changed - therefore you have to create the iterator AFTER you have added everything to the stack, not before that.

You can read more about it here: http://www.journaldev.com/378/how-to-avoid-concurrentmodificationexception-when-using-an-iterator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top