Using Stacks

     

Stacks are like Pez dispensers. Stacks are very similar to arrays, and so we'll discuss them here. Many internal data structures are stored as stacks within Java. The stack operates on a last in, first out basis. You can create your own stack, or you can use an instance of java.util.Stack.

The java.util.Stack class extends java.util.Vector , which is a type of collection. The two main operations you use with a stack are pop() and push() . You can also peek() to see the item on the top of the stack. Finally, you can search the stack for an item, and you can determine if the stack is empty.

UsingStacks.java

 

 package net.javagarage.arrays; import java.util.Stack; /**  * <p>Does stuff with java.util.Stack  * @author eben hewitt  */ public class UsingStacks { public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.push(41); stack.push(42); stack.push(43); //get first in line System.out.println("First: " + stack.peek()); //prints 43 //is stack empty? System.out.println("is empty? " + stack.empty()); //false System.out.println("search: " + stack.search(42)); //search returns 2this is 1-based!!! } } 

Note that you need to compile this code with the 5.0 compiler because it takes advantage of the new generics autoboxing feature (we're adding int primitives to the stack, which is declared to accept only Integer objects ”they get automatically wrapped).



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net