I want to use "Last Come First Serve" mechanism in my application. For that Stacks are the best choice. Some time back I implemented my own stack and can reuse that.
Does Java also provides Stack? Please give some examples.
Thanks.
Printable View
I want to use "Last Come First Serve" mechanism in my application. For that Stacks are the best choice. Some time back I implemented my own stack and can reuse that.
Does Java also provides Stack? Please give some examples.
Thanks.
Something like this, a simple stack
Code:import java.util.Stack;
public class StacksDemo
{
public static void main(String[] arguments)
{
Stack newStack = new Stack();
newStack.push("10");
newStack.push("20");
newStack.push("30");
newStack.push("40");
// and many more items to push
while(!newStack.empty())
{
System.out.println(newStack.pop());
}
}
}
Just tested it. Works fine but I have a questions.
This works perfectly fine thus violating the stacks principle.Code:System.out.println(newStack.get(1));
Reason is this. Even you use this stack, all the elements are either in an Array or Linked list. So,
what have done is just find the proper element.Code:newStack.get(1)
Keep in mind that element index start from zero. If you start from zero to locate the elements you can see that stack principle not violated. ;)
I think that is what you are talking about.
Thanks Eranga for the explanation.
When we POP, then the element is removed from the stack. I was assuming pop and get does the same job but its not the case.
No there is a different.
What the POP done is, removes the object at the top of the stack and returns that object as a value, simple value you PUSH. You can't indexing, and what you can do is POP values until the stack has at least one element or any other predefined condition.
Like this,In get() you can indexing, if you want. Definition like this,Code:pop()
According to your code, you use get() to find the 2nd element of the stack. I told you that all the stack elements are in an array or linked list.Code:get(int index)
Important thing to remember, you can use get() in different aspect, and my explanation is based on your code. If you can refer the documentation, you can find lots of explanations on it.
Hope this is helpful to you :)
Thanks for the detailed response.
You cleared my concepts .... Thanks mate...
Keep posting :D
You are welcome pal. I love to give away that what I know for my friends.
So, your question is SOLVED. Nice...