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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With