Вопрос

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());
        }

    }

}
Это было полезно?

Решение

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);
}

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top