import java.util.Iterator;
import java.util.Stack;
public class StackExample {
public static void main(String args[]){
Stack<String> sk = new Stack<String>();
sk.push("Hello");
sk.push("Hello1");
sk.push("Hello2");
sk.push("Hello3");
System.out.println("The Values of Stack" +sk);
Iterator it=sk.iterator();
System.out.println("Size before pop() :"+sk.size());
while(it.hasNext())
{
String iValue=(String)it.next();
System.out.println("Iterator value :"+iValue);
}
String value =(String)sk.pop();
System.out.println("value :"+value);
System.out.println("Size After pop() :"+sk.size());
}
}
Can anyone explain me the below questions.
while(it.hasNext()){
String iValue=(String)it.next();
System.out.println("Iterator value :"+iValue);
}
-
Why do we iterate in this manner and what does the hasNext and next
do? Can i not do the same with an for loop.String value =(String)sk.pop(); -
What does the (String)sk.pop means… why does it not compile when i
remove the (String) -
Can anyone lead me to some good and complex Stack examples in Java
The
nextfetches the next value from the iterator, andhasNexttells you whether or not there is a next value available.Yes, you could do the same with a for loop:
should do just as fine for instance.
When you pop an element of a stack, you remove the “top” (last inserted) element. The
(String)part is a cast. This is neccesary if thepopreturns anObjectand (you know it’s actually aString) and you want to store it in aStringreference.Complex stack examples? Uhm, no, I can’t. A stack basically provide push and pop which are really simple. Whatever the example would be, it would be complex due to something else than the use of a stack, which won’t help you understand stacks any better 🙂