|
Here's the Stack example, translated to using generics:
package examples;
import java.util.Stack;
public class StackExample
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();
stack.push("Mary");
stack.push("Frank");
stack.push("Joe");
stack.push("Sylvia");
stack.push("Vanessa");
while ( !stack.empty() )
{
String name = stack.pop(); // Note NO required cast
System.out.println(name);
}
}
}
|
This program outputs the following (same as the original):
Vanessa
Sylvia
Joe
Frank
Mary
Changing the Type
To show how you can change the type, here's an example of using a stack with
Integer elements:
package examples;
import java.util.Stack;
public class IntegerStackExample
{
public static void main(String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
while ( !stack.empty() )
{
Integer value = stack.pop(); // Note NO required cast
System.out.println(value);
}
}
}
|
which produces the following output:
5
4
3
2
(Notice that I'm using "autoboxing" on both the input and the output.)
|