50 lines
1.8 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: containers/Stacks.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// Demonstration of Stack Class.
import java.util.*;
import static net.mindview.util.Print.*;
enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER }
public class Stacks {
public static void main(String[] args) {
2015-05-05 11:20:13 -07:00
Stack<String> stack = new Stack<>();
2015-04-20 15:36:01 -07:00
for(Month m : Month.values())
stack.push(m.toString());
print("stack = " + stack);
// Treating a stack as a Vector:
stack.addElement("The last line");
print("element 5 = " + stack.elementAt(5));
print("popping elements:");
while(!stack.empty())
printnb(stack.pop() + " ");
// Using a LinkedList as a Stack:
2015-05-05 11:20:13 -07:00
LinkedList<String> lstack = new LinkedList<>();
2015-04-20 15:36:01 -07:00
for(Month m : Month.values())
lstack.addFirst(m.toString());
print("lstack = " + lstack);
while(!lstack.isEmpty())
printnb(lstack.removeFirst() + " ");
// Using the Stack class from
// the Holding Your Objects Chapter:
net.mindview.util.Stack<String> stack2 =
2015-05-05 11:20:13 -07:00
new net.mindview.util.Stack<>();
2015-04-20 15:36:01 -07:00
for(Month m : Month.values())
stack2.push(m.toString());
print("stack2 = " + stack2);
while(!stack2.empty())
printnb(stack2.pop() + " ");
}
} /* Output:
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
*///:~