Java Generics

Generics was introduced with J2SE 5.With the help of generics programmers can write generic code for all the types. In Java we can use generics with class and methods.

Advantage of generics

  • Compile-time checking
  • Type-safety
  • No need of type casting

package com.startwithjava;
public class GenericTest<T>{
T value;
public void set(T value){
this.value=value;
}
public T get(){
return value;
}
}

package com.startwithjava;
public class GenericsExampleTest {
	public static void main(String args[]){
		GenericTest<String> g1 = new GenericTest<String>();
		g1.set("Gaurav");
		System.out.println("Value="+g1.get());
	}
}

package com.startwithjava;

public class GenericsMethodTest {

public static void display(E[] elements){

for(int i=0;i<elements.length;i++){

System.out.println("Value of element at position "+i+"="+elements[i]);
}
}
public static void main(String args[]){
//int of array
Integer[] intArray = { 10, 20, 30, 40, 50 };
System.out.println("Display elements for integer array");
display(intArray);

//String array

String[] strArray = {"Aman","Sohan","Raj" };
System.out.println("Display elements for String array");
display(strArray);
}

}

Leave a Reply