Generics in Java (Generic Classes and Methods in Java)

Other Java Topics

Generics in Java allows us to write one function and then used this same function to perform operations on different data types.

To clarify, we are going to write the programs and then see how it works. In this way, it would become very clear. First we would write a program, that does not use generics. Then we would write similar program using generics. Take a look at the program in Listing 1.0.

/*
 * Program to Illustrate Generics
 * Written by: Kindson The Genius
 */
public class RunProgs {

	public static void main(String[] args) {
		Integer[] IntArray = {1,2,3,4,5, 6,7, 8};
		Character[] CharArray = {'k','i','n','d','s', 'o', 'n'};
		String [] StringArray = {"Osoo", "Adii", "Ottie","Jackie", "Kany"};
		
		printArray(IntArray);
		printArray(CharArray);
		printArray(StringArray);
	}	
	
	public static void printArray(Integer[] ar) //for printing Integer array
	{
		for(Integer x:ar)
			System.out.printf("%s ", x);
		System.out.println();			
	}
	
	public static void printArray(Character[] ar) //for printing Character array
	{
		for(Character x:ar)
			System.out.printf("%s ", x);
		System.out.println();			
	}
	
	public static void printArray(String [] ar) //for printing String array
	{
		for(String x:ar)
			System.out.printf("%s ", x);
		System.out.println();			
	}
}

Listing 1.0: Illustration of Generic Methods

In the program in Listing 1.0, we see three similar methods called printArray(). This method printArray() is what is known as overloaded method. So, generics is a construct used to eliminate the use of several overloaded methods.

The first one is for printing Integer arrays. The second one is for printing character arrays and the third is for printing String arrays.

Imagine we have other types of arrays: say double, float, short etc. It means we would need to continue to create the same method over and over. This is where generics come in.

Generics help us define a single generic method that can handle any data type! First make sure you run the above code by copying and pasting in your java IDE. Also try to remove one of the methods, and notice that there would be a compile-time error.

 

How to Create a Generic Method

A single generic method with the same is written to handle the operati

ons with different types of arguments. Based on the argument passed to the method, the compiler performs the required operation

Generic methods are defined based on the following rules:

  • Generic method declaration have a type parameter that is enclosed in angle brackets e.g <T> . This comes before the return type
  • The type parameter contains either one or more type parameters which are seperated by commas.
  • The type parameter is used as placeholders for the type of arguments that is expected by the generic method. The type parameter can also be used to specify the return type
  • The body of the generic method is implemented like any other method.

Let’s now rewrite the program in Listing 1.0, this time using one single generic method.

/*
 * Program to Illustrate Generics
 * Written by: Kindson The Genius
 */
public class RunProgs {

	public static void main(String[] args) {
		Integer[] IntArray = {1,2,3,4,5, 6,7, 8};
		Character[] CharArray = {'k','i','n','d','s', 'o', 'n'};
		String [] StringArray = {"Osoo", "Adii", "Ottie","Jackie", "Kany"};
		
		printArray(IntArray);
		printArray(CharArray);
		printArray(StringArray);
	}	
	 
	public static <T> void printArray(T[] ar) //A single generic method
	{
		for(T x: ar)
		{
			System.out.printf("%s ", x);
		}
		System.out.println();
	}
}

Listing 1.1:  Using a single Generic method

Copy the program in Listing 1.1 and run it.  You will find out that it yields the same results as the previous program. This is the strength of generics, it eliminates having to write several overloaded methods.

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

One thought on “Generics in Java (Generic Classes and Methods in Java)

  1. Pingback: Generics Tutorial in Java – Part 1 | Coding and More

Leave a Reply

Your email address will not be published. Required fields are marked *