jesus Sandoval
jesus Sandoval

Reputation: 71

On which condition will IllegalStateException be thrown?

When working with an iteration, in which condition will IllegalStateException be thrown? I'm working on an assignment and it's multiple-choice:

a) calling remove after calling next
b) calling next after calling previous
c) calling remove after calling remove
d) calling remove after calling previous

What I found in the "API docs" is that if the next method has not yet been called, or the remove method has already been called after the last call to the next method.

So the answer then must be "a", but I'm told it's wrong. Why is my reasoning wrong, and what's the correct answer?

Upvotes: 1

Views: 673

Answers (1)

Jim Barrows
Jim Barrows

Reputation: 3634

You have a list [a, b, c, d, e]. A pointer N starts out pointing at nothing. This is the standard starting position for an iterator in Java.

Scenario A) - call next, N is now pointing at a. Call remove, a is gone and the list is [b, c, d, e], N is pointing at nothing.

Scenario B) Call previous, N is now pointing at e. Call next, N is now pointing at a.

Scenario C) Call next, N is pointing at a. Call remove, a is gone, N is pointing at nothing. Call remove,IllegalStateExceptionis thrown.N` is pointing at nothing, so nothing can be removed.

Scenario D) Call previous, N is pointing at e. Call remove, e is gone, N is pointing at nothing.

Scenario E) Call remove, N is pointing at nothing, so IllegalStateException is thrown.

Upvotes: 2

Related Questions