Search code examples
javadata-structuresstackconcurrentmodification

How to call toString() method of all objects in a Stack?


I have a class (myObject) that has its own toString() method. I then made another class called myStack and it extends Stack. This class is supposed to be a stack of myObject objects.

When I try to iterate over the stack using iterator to print each object, it throws a ConcurrentModificationException.

Here is my code:

public class myStack extends Stack<myObject> {

    Iterator<myObject> iter = this.iterator();

    public void printStack(){

        while(iter.hasNext()){

            myObject temp = iter.next();

            System.out.print(temp.toString());

        }

    }

} 

I am not modifying the stack while I'm iterating over it, so I dont understand why the exception is being thrown.


Solution

  • Your problem is when you're getting the iterator. You're getting it on myStack object creation (please rename the class to MyStack), then modifying the stack, then using the iterator, and this won't fly since you're using the iterator after the stack has been modified. Instead you need to extract the iterator just prior to use at the top of the printStack() method, so that it is a valid and stable iterator, one that represents the state of the stack at that time.

    public class MyStack extends Stack<myObject> {
    
        public void printStack() {
            Iterator<myObject> iter = this.iterator(); // *** here***
            while(iter.hasNext()) {
                myObject temp = iter.next();
                System.out.print(temp.toString());
            }
        }
    

    As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.