Java Generics Stack Example: The following program creates generics stacks storing all ints, doubles, chars and strings. Java 5 enhanced for loop is used to print the elements.
Two Java Generics Stack Examples are given on Java Generics Stack.
- First one is general stack storing any data types. The methods push, peek, pop, size etc. are used.
- The present one is generics stack storing similar or specific type of elements. Enhanced for loop (foreach) is used to iterate the elements.
It is advised to read the first stack program before this where you get acquainted with Stack, methods and constructors available etc.
import java.util.*;
public class GenericsStack
{
public static void main(String args[])
{ // 1. Stack that stores only int values
Stack st1 = new Stack(); // generics int stack
st1.add(10);
st1.add(20);
st1.add(30);
st1.add(40);
System.out.print("Printing int stack: ");
for(int k : st1)
{
System.out.print(k + " ");
}
// 2. Stack that stores only strings
Stack st2 = new Stack(); // generics string stack
st2.add("Believe");
st2.add("atleast");
st2.add("one");
System.out.print("\nPrinting string stack: ");
for(String k : st2)
{
System.out.print(k + " ");
}
// 3. Stack that stores only chars
Stack st3 = new Stack(); // generics char stack
st3.add('A');
st3.add('B');
st3.add('C');
System.out.print("\nPrinting char stack: ");
for(char k : st3)
{
System.out.print(k + " ");
}
// 4. Stack that stores only double
Stack st4 = new Stack(); // generics double stack
st4.add(10.5);
st4.add(20.5);
st4.add(30.5);
System.out.print("\nPrinting double stack: ");
for(double k : st4)
{
System.out.print(k + " ");
}
// printing with iterator
System.out.print("\nUsing Iterator: ");
Iterator it1 = st2.iterator();
while(it1.hasNext())
{
System.out.print(it1.next() + " ");
}
}
}

Output screen of Java Generics Stack
Four Java generics stack objects, st1, st2, st3 and st4 are created that stores only ints, strings, characters and doubles values. With enhanced for loop (some people call it as foreach), all the elements of stacks are printed. To illustrate an example, it1 values are printed with Iterator interface also.
Pass your comments and suggestions to improve the quality of this tutorial “Java Generics Stack”.