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);
}
- What is the difference between these two?
- Any Advantage if i choose one among them?
- Which is the preferred way of iterating?
Not much. The for-each loop construct actually relies on the iterator behind the curtains.
Further reading:
Mostly readability I would assume.
(If you need to access the
iterator.remove()method, then obviously you would need to go with the explicitIteratorapproach.) However, keep in mind that it’s an optional operation and may not be supported by the underlyingStackimplementation you’re using.Besides, the point of a
Stackstructure is that you don’t remove elements in the middle.Use the for-each approach, if that works for you.