View RSS Feed

Algorithm and Data Structure

Java's Stack Class

Rate this Entry
by , 02-19-2012 at 07:16 AM (556 Views)
Stack is considered to be a data structure which used last in first out policy. New elements could be added or removed to/from the top of Stack. Queue uses First in First out mechanism as compared to Stack.

Java Code: Stack usage is explained by this code
Stack myStack = new Stack();
myStack.push("1");
myStack.push("2");
myStack.push("3");
//look at top object ("3"), without taking it off the stack.    
Object topObj = stack.peek();
Object obj3 = stack.pop(); //the string "3" is at the top of the stack.
Object obj2 = stack.pop(); //the string "2" is at the top of the stack.
Object obj1 = stack.pop(); //the string "1" is at the top of the stack.
• The push() method pushes an element at the Stack’s top.
• The peek() method gets the top element without removal from Stack.
• The pop() method gets the top element. It also plays a role in its removal from Stack.

Searching the Stack

On Stack, an element could also be searched. For searching, search() method is used. For matching all the elements to the value, equal() method of object is called.


Java Code: Stack search mechanism is explained by this given code.
Stack myStack = new Stack();
myStack.push("1");
myStack.push("2");
myStack.push("3");
int index = myStack.search("3");     //index = 3

Submit "Java's Stack Class" to Facebook Submit "Java's Stack Class" to Digg Submit "Java's Stack Class" to del.icio.us Submit "Java's Stack Class" to StumbleUpon Submit "Java's Stack Class" to Google

Tags: stack class Add / Edit Tags
Categories
Stack

Comments