Monday, 10 March 2014

Generic Interface

A generic interface is defined with the following format:

interface name<T1, T2, ..., Tn> { /* ... */ }

The type parameter section, delimited by angle brackets (<>), follows the interface name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

A type variable 'T' can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

interface StackModel<T>{
 void push(T data);
 T pop();
}
    
class Stack<T> implements StackModel<T>{
 Object arr[];
 int top=-1;
 int size;

 Stack(int size){
  this.size=size;
  arr = new Object[size];
 }

 public void push(T data){
  if( top < size-1){
   top++;
   arr[top] = data;
  }
  else{
   System.out.println("Stack is full");
  }
 }

 public T pop(){
  if(top < 0 ){
   System.out.println("Stack is Empty");
   return null;
  }
  else{
   System.out.println("Element deleted is " + arr[top]);
   T val = (T) arr[top];
   top--;
   return val;
  }
 }

 public static void main(String args[]){
  Stack<String> stringStk = new Stack<String> (5);
  Stack<Integer> intStk = new Stack<Integer> (5);

  stringStk.push("HI");
  stringStk.push("abc");
  stringStk.pop();

  intStk.push(10);
  intStk.push(20);
  intStk.pop();
 }
}
   
Output
Element deleted is abc
Element deleted is 20
    


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment