Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In this section, we investigate class Stack in the Java utilities package (java.util). Section 16.5.3 discussed class Vector, which implements a dynamically resizable array. Class Stack extends class Vector to implement a stack data structure. Autoboxing occurs when you add a primitive type to a Stack, because class Stack stores only references to objects. Figure 16.16 demonstrates several Stack methods. For the details of class Stack, visit java.sun.com/javase/6/docs/api/java/util/Stack.html.
Code View:
Scroll
/
Show All 1 // Fig. 16.16: StackTest.java 2 // Program to test java.util.Stack. 3 import java.util.Stack; 4 import java.util.EmptyStackException; 5 6 public class StackTest 7 { 8 public StackTest() 9 { 10 Stack< Number > stack = new Stack< Number >(); 11 12 // create numbers to store in the stack 13 Long longNumber = 12L; 14 Integer intNumber = 34567; 15 Float floatNumber = 1.0F; 16 Double doubleNumber = 1234.5678; 17 18 // use push method 19 stack.push( longNumber ); // push a long 20 printStack( stack ); 21 stack.push( intNumber ); // push an int 22 printStack( stack ); 23 stack.push( floatNumber ); // push a float 24 printStack( stack ); 25 stack.push( doubleNumber ); // push a double 26 printStack( stack ); 27 28 // remove items from stack 29 try 30 { 31 Number removedObject = null; 32 33 // pop elements from stack 34 while ( true ) 35 { 36 removedObject = stack.pop(); // use pop method 37 System.out.printf( "%s popped\n", removedObject ); 38 printStack( stack ); 39 } // end while 40 } // end try 41 catch ( EmptyStackException emptyStackException ) 42 { 43 emptyStackException.printStackTrace(); 44 } // end catch 45 } // end StackTest constructor 46 47 private void printStack( Stack< Number > stack ) 48 { 49 if ( stack.isEmpty() ) 50 System.out.print( "stack is empty\n\n" ); // the stack is empty 51 else // stack is not empty 52 { 53 System.out.print( "stack contains: " ); 54 55 // iterate through the elements 56 for ( Number number : stack ) 57 System.out.printf( "%s ", number ); 58 59 System.out.print( "(top) \n\n" ); // indicates top of the stack 60 } // end else 61 } // end method printStack 62 63 public static void main( String args[] ) 64 { 65 new StackTest(); 66 } // end main 67 } // end class StackTest |
stack contains: 12 (top)
stack contains: 12 34567 (top)
stack contains: 12 34567 1.0 (top)
stack contains: 12 34567 1.0 1234.5678 (top)
1234.5678 popped
stack contains: 12 34567 1.0 (top)
1.0 popped
stack contains: 12 34567 (top)
34567 popped
stack contains: 12 (top)
12 popped
stack is empty
java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at java.util.Stack.pop(Unknown Source)
at StackTest.<init>(StackTest.java:36)
at StackTest.main(StackTest.java:65) |