Generic Stack Class Demo Example in java util Package

class Stack<T>
{ int top = -1; int size;
Object a[];
Stack(int size)
{ this.size = size;
a = new Object[size];
}
void push(T obj)
{ if(top == size-1)
{ System.out.println("Stack Full");
return;
}
top = top + 1; a[top] = obj;
}
T pop()
{ if(top ==  -1)
{ return null;
}
T obj = (T)a[top];
top = top - 1;
return obj;
}
void display()
{
for(int i = top; i>=0; i--)
{
T obj1 = (T) a[i];
System.out.println(obj1);
}
}
}

class Student
{
int rollno;
String name;
String phone;
public String toString()
{
return  rollno + ", " + name + ", " + phone;
}
}

class GenericStackDemo
{ public static void main(String args[])
{ Stack st1 = new Stack(10);
st1.push("Devesh");
st1.push(10);
st1.push(new Double(5.4));
System.out.println("Stack of type Object:");
st1.display();
Stack<String> st2 = new Stack<String>(20);
st2.push("Rakesh");
st2.push("Rahul");
st2.push("Devesh");
st2.push("Manohar");
//st2.push(20); //- Compile time error
System.out.println("\nStack of type String:");
st2.display();
Stack<Student> st3 = new Stack<Student>(10);
Student s1 = new Student();
s1.rollno = 1; s1.name = "Rahul"; s1.phone = "2590381";
Student s2 = new Student();
s2.rollno = 5; s2.name = "Devesh"; s2.phone = "9829059033";
Student s3 = new Student();
s3.rollno = 3; s3.name = "Rakesh"; s3.phone = "2590381";
Student s4 = new Student();
s4.rollno = 2; s4.name = "Manohar"; s4.phone = "2590381";
Student s5 = new Student();
s5.rollno = 4; s5.name = "Prateek"; s5.phone = "2590381";
st3.push(s1);
st3.push(s2);
st3.push(s3);
st3.push(s4);
st3.push(s5);
//st3.push("Devesh"); //- will not compile
System.out.println("\nStack of type Student:");
st3.display();
Stack<Integer> s = new Stack<Integer>(10);
st1 = st3; //- will not compile;
}
}

Comments