Wednesday, 15 May 2013

Example showing the use and importance of Generics

An Example of Generics Usage . Learn this and know the importane if Generics in java . So much of the code has been saved in Java API because of Generics especially in the Collection API . After reading the below short program u will know why ?

public class Stack<E extends Object> {

Object o[];
int limit;
int sp=0;
public Stack(int size){
o=new Object[size];
limit=size;
}
public void push(E e){
if(sp==limit){
System.out.println("Stack OverFlow");
}
else{
o[sp]=e;
sp++;
}
}
public E pop(){
E e = null;
if(sp==0){
System.out.println("Stack UnderFlow");
}
else{
sp--;
e= (E) o[sp];
}
return e;
}
}

Usage of above class :-

Demo.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package code;

/**
*
* @author Aspire
*/
public class Demo {
public static void main(String...arg){
Stack<Integer> intStack=new Stack<Integer>(3);

intStack.push(1);
intStack.push(2);
intStack.push(3);
intStack.push(4);

System.out.println(intStack.pop());
System.out.println(intStack.pop());
System.out.println(intStack.pop());

Stack<String> stringStack=new Stack<String>(3);

stringStack.push("Aspire");
stringStack.push("Institute");
stringStack.push("Best Place");
stringStack.push("for learning java");

System.out.println(stringStack.pop());
System.out.println(stringStack.pop());
System.out.println(stringStack.pop());

Stack<Animal> animalStack=new Stack<Animal>(3);
Animal a1=new Animal();
a1.name="Donkey";
animalStack.push(a1);

Animal a2=new Animal();
a2.name="Dog";
animalStack.push(a2);

Animal a3=new Animal();
a3.name="Horse";
animalStack.push(a3);

System.out.println(animalStack.pop().name);
System.out.println(animalStack.pop().name);
System.out.println(animalStack.pop().name);

}
}

class Animal{
String name;
}

In this way u can use the same Stack Class for Float ,Double , or for any userdefined class u want .

No comments:

Post a Comment