2
Stack<String> sk = new Stack<String>();

sk.push("Hello");
sk.push("Hello1");
sk.push("Hello2");

There are two ways i am iterating this Stack Object.

for(String s : sk){
   System.out.println("The Values of String in SK" +sk);
}

// Way two..

Iterator<String> it=sk.iterator();
    while(it.hasNext())
    {
        String iValue=(String)it.next();
        System.out.println("Iterator value :"+iValue);
    }
  1. What is the difference between these two?
  2. Any Advantage if i choose one among them?
  3. Which is the preferred way of iterating?

6 Answers 6

4

The Iterator has the advantage that you can remove elements from the collection while iterating over it. Foreach may throw ConcurrentModificationExceptions there.

If you don't need that, I prefer the former way because it is easier to read.

Sign up to request clarification or add additional context in comments.

1 Comment

Why would he use a Stack if he needs to remove elements from the middle of the collection?
2

1. What is the difference between these two?

Not much. The for-each loop construct actually relies on the iterator behind the curtains.

Further reading:

2. Any Advantage if i choose one among them?

Mostly readability I would assume.

(If you need to access the iterator.remove() method, then obviously you would need to go with the explicit Iterator approach.) However, keep in mind that it's an optional operation and may not be supported by the underlying Stack implementation you're using.

Besides, the point of a Stack structure is that you don't remove elements in the middle.

3. Which is the preferred way of iterating?

Use the for-each approach, if that works for you.

Comments

2

with the Iterator you can prevent a java.util.ConcurrentModificationException, when you modify the list while looping over them. Iterator.remove()

Comments

2

From Effective Java, by Joshua Bloch:

The for loop, in both its traditional and for-each forms, allows you to declare loop variables, limiting their scope to the exact region where they’re needed. (This region consists of the body of the loop as well as the initialization, test, and update preceding the body.)Therefore, prefer for loops to while loops, assuming the contents of the loop variable aren’t needed after the loop terminates.

To make it short:

  • the for-each loop is always type safe

  • the for-each loop is less prone to copy/paste errors (copy/paste iterator1 twice in your code!)

  • the for-each loop allows you to minimize the scope of local variables

  • the for-each loop is easier to read!

In summary, prefer for-each loops to while loops when you do not explicitly need a while loop.

Comments

1

Choosing between For each and an Iterator is just a matter of convenience. For each loop looks a bit cryptic especially to those who are used to the traditional for loop. The downside with Iterators, however, is that you've to cast the Object from the next() to the appropriate type, although your collection is not typed. With For each, everything is happening behind the scenes.

1 Comment

Actually, since java 1.5, Iterator is generic, so you don't need a cast if you added the appropriate generic parameters to your collection and iterator
1

What is the difference between these two?

Nothing. Except for the extra code

Any Advantage if I choose one among them?

Yes. If you use the newer one (foreach), you have fewer lines and are therefore easier to read.

Which is the preferred way of iterating?

The foreach loop

You may want to read Nuances of the Java 5.0 for-each Loop and the official for-each loop tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.