Using an iterator interface or for each statement in Java

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

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

There are two ways: I repeat 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);
    }
  • What is the difference between the two?
  • Any advantage if I choose one of them?
  • What is the preferred way to iterate?
+2
source share
6 answers

1. What is the difference between the two?

Little. The design for each loop actually relies on an iterator behind the curtains.

Further reading:

2. Any advantage if I choose one of them?

Mostly readability I would suggest.

( iterator.remove(), , , Iterator.) , Stack, .

, Stack , .

3. ?

for-each, .

+2

Iterator , , . Foreach ConcurrentModificationExceptions.

, , .

+4

Iterator java.util.ConcurrentModificationException, , . Iterator.remove()

+2

Java, :

for, , for-each , , , . ( , , .) for while , , arent, .

:

  • for-each

  • for-each / (/ iterator1 !)

  • for-each

  • for-each !

, for-each while , while.

+2

Iterator . , , . Iterator s , Object next() , . .

+1

?

.

, ?

. (foreach), , , .

What is the preferred way to iterate?

Foreach loop

You can read the Java 5.0 Nuances for each cycle and the official tutorial for each cycle.

+1
source

All Articles