The perfect place for easy learning...

Java Programming

×

Topics List


Generics in Java





The java generics is a language feature that allows creating methods and class which can handle any type of data values. The generic programming is a way to write generalized programs, java supports it by java generics.

The java generics is similar to the templates in the C++ programming language.

🔔 Most of the collection framework classes are generic classes.

🔔 The java generics allows only non-primitive type, it does not support primitive types like int, float, char, etc.

The java generics feature was introduced in Java 1.5 version. In java, generics used angular brackets “< >”. In java, the generics feature implemented using the following.

  • Generic Method
  • Generic Classe

Generic methods in Java

The java generics allows creating generic methods which can work with a different type of data values.

Using a generic method, we can create a single method that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.

Let's look at the following example program for generic method.

Example - Generic method
public class GenericFunctions {
	
	public <T, U> void displayData(T value1, U value2) {
		
		System.out.println("(" + value1.getClass().getName() + ", " + value2.getClass().getName() + ")");
	}

	public static void main(String[] args) {
		
		GenericFunctions obj = new GenericFunctions();
		
		obj.displayData(45.6f, 10);
		obj.displayData(10, 10);
		obj.displayData("Hi", 'c');
	}

}

In the above example code, the method displayData( ) is a generic method that allows a different type of parameter values for every function call.

Generic Class in Java

In java, a class can be defined as a generic class that allows creating a class that can work with different types.

A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.

Let's look at the following example program for generic class.

Example - Generic class
public class GenericsExample<T> {
	T obj;
	public GenericsExample(T anotherObj) {
		this.obj = anotherObj;
	}
	public T getData() {
		return this.obj;
	}
	
	public static void main(String[] args) {
		
		GenericsExample<Integer> actualObj1 = new GenericsExample<Integer>(100);
		System.out.println(actualObj1.getData());
		
		GenericsExample<String> actualObj2 = new GenericsExample<String>("Java");
		System.out.println(actualObj2.getData());
		
		GenericsExample<Float> actualObj3 = new GenericsExample<Float>(25.9f);
		System.out.println(actualObj3.getData());
	}
}