Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using iterator interface or for each statement in Java

Tags:

java

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?
like image 741
John Cooper Avatar asked Jun 04 '26 00:06

John Cooper


1 Answers

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.

like image 176
Arnout Engelen Avatar answered Jun 05 '26 12:06

Arnout Engelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!