60 lines
2.0 KiB
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// collectionsindepth/Stacks.java
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Demonstration of Stack Class
2015-06-15 17:47:35 -07:00
import java.util.*;
enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER }
public class Stacks {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
for(Month m : Month.values())
stack.push(m.toString());
2015-11-03 12:00:44 -08:00
System.out.println("stack = " + stack);
2015-06-15 17:47:35 -07:00
// Treating a stack as a Vector:
stack.addElement("The last line");
2016-01-25 18:05:55 -08:00
System.out.println(
"element 5 = " + stack.elementAt(5));
2015-11-03 12:00:44 -08:00
System.out.println("popping elements:");
2015-06-15 17:47:35 -07:00
while(!stack.empty())
2015-11-03 12:00:44 -08:00
System.out.print(stack.pop() + " ");
2015-06-15 17:47:35 -07:00
// Using a LinkedList as a Stack:
LinkedList<String> lstack = new LinkedList<>();
for(Month m : Month.values())
lstack.addFirst(m.toString());
2015-11-03 12:00:44 -08:00
System.out.println("lstack = " + lstack);
2015-06-15 17:47:35 -07:00
while(!lstack.isEmpty())
2015-11-03 12:00:44 -08:00
System.out.print(lstack.removeFirst() + " ");
2015-06-15 17:47:35 -07:00
// Using the Stack class from
2015-12-15 11:47:04 -08:00
// the Collections Chapter:
onjava.Stack<String> stack2 =
new onjava.Stack<>();
2015-06-15 17:47:35 -07:00
for(Month m : Month.values())
stack2.push(m.toString());
2015-11-03 12:00:44 -08:00
System.out.println("stack2 = " + stack2);
2015-06-15 17:47:35 -07:00
while(!stack2.empty())
2015-11-03 12:00:44 -08:00
System.out.print(stack2.pop() + " ");
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
stack = [JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY,
AUGUST, SEPTEMBER, OCTOBER, NOVEMBER]
element 5 = JUNE
popping elements:
The last line NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE
MAY APRIL MARCH FEBRUARY JANUARY lstack = [NOVEMBER,
OCTOBER, SEPTEMBER, AUGUST, JULY, JUNE, MAY, APRIL, MARCH,
FEBRUARY, JANUARY]
NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE MAY APRIL MARCH
FEBRUARY JANUARY stack2 = [NOVEMBER, OCTOBER, SEPTEMBER,
AUGUST, JULY, JUNE, MAY, APRIL, MARCH, FEBRUARY, JANUARY]
NOVEMBER OCTOBER SEPTEMBER AUGUST JULY JUNE MAY APRIL MARCH
FEBRUARY JANUARY
2015-09-07 11:44:36 -06:00
*/