Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Understanding the Generic Methods in Java

In this lesson, you will learn.

  • Creating Generic Method
  • Examples
  • Adding a Generic Method inside a Generic Class
  • Example

 

Generic Method

Imagine we need a method that takes different types of data and does something. We can create a Generic method for this and reuse it in code.

 

Syntax

public <Type Parameter> [Return Type] [MethodName](Argument list…)
{
   //Method Body
}

 

Example: Declaring a Generic Method

public <T> T methodName(T param) {
    // method body
    return param;
}

 

A generic method is declared with type parameters that are specified before the method’s return type.

1. <T>: It is a type parameter section, enclosed in angle brackets that can declare one or more type parameters separated by commas. These parameters act as placeholders for the types that are specified when the method is called.

2. ReturnType T: A method return type can be a generic type parameter.

3. methodName: The name of the method.

4. Argument List(T param): The list of parameters, which can also use the type parameters.

 

Example-1: Displaying Different Types of Value Using Generic Method

//Define a generic method
public static <T> void callMe(T data) {
    System.out.println(data);
}

//Calling the method over different datatypes
callMe("Hi");
callMe(15);
callMe(25.37);
callMe(15L);
callMe(new Car("Ford", "White", 5));

/* output:
    Hi
    15
    25.37
    15
    generics.Car@45244cd7
*/ 

 

Example-2: Displaying an Array Elements Using A Generic Method

A generic print method is useful because it can handle any type of data, from integers, and strings to the custom objects.

This method leverages a single implementation to print different types of data structures like arrays or collections.

 public class Printer {

    // Generic method to print array elements
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Integer[] integerArray = {1, 2, 3, 4, 5};
        String[] stringArray = {"Hello", "World", "Generics", "in", "Java"};

        System.out.println("Integer Array:");
        printArray(integerArray);  // Outputs: 1 2 3 4 5 

        System.out.println("String Array:");
        printArray(stringArray);   // Outputs: Hello World Generics in Java 
    }
}

Explanation:

  • The method printArray is generic, specified by <T>, which means it can accept an array of any object type.
  • Inside the method, it iterates over an array of type T and prints each element. This is a highly reusable method that works with any type of array.

 

Example-3: Generic Method to Return the Middle Element of an Array

package genericmethod;

public class ArrayUtils {
	public static <T> T getMiddle(T[] array) {
		return array[array.length / 2];
	}

	public static void main(String[] args) {
		Integer[] intArray = {1, 2, 3, 4, 5};
		String[] strArray = {"hello", "world", "generics", "java"};
		System.out.println("Middle element (int): " 
				+getMiddle(intArray));
		System.out.println("Middle element (String): " 
				+getMiddle(strArray));
	}
}

Output

Middle element (int): 3
Middle element (String): generics

 

Example 4: Generic Method to Swap Elements in an Array

package genericmethod;

import java.util.Arrays;

public class SwapUtils {

	public static <T> void swap(T[] a, int i, int j) {
		T temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}

	public static void main(String[] args) {
		String[] strArray = {"one", "two", "three"};
		System.out.println("Array before swap: " 
				+Arrays.toString(strArray));
		swap(strArray, 0, 2);
		System.out.println("Array after swap: " 
				+Arrays.toString(strArray));
	}
}

 

Output

Array before swap: [one, two, three]
Array after swap: [three, two, one]

 

2. Adding a Generic Method inside a Generic Class

You can combine generic methods with generic classes to enhance flexibility and reusability.

This combination allows you to define methods within a class that can operate on types independent of the class’s generic type, or in conjunction with it.

 

Example: Generic ‘Pair’ Class with a Generic Method

package genericmethod;

class Pair<K, V> {
	private K key;
	private V value;

	// Constructor
	public Pair(K key, V value) {
		this.key = key;
		this.value = value;
	}

	// Getters
	public K getKey() {
		return key;
	}

	public V getValue() {
		return value;
	}

	// A generic method to compare two pairs' keys or values
	public static <T> boolean compare(T part1, T part2) {
		return part1.equals(part2);
	}
}

public class GenericMethodPair {

	public static void main(String[] args) {
		
		Pair<Integer, String> pair1 = new Pair<>(1, "Apple");
        Pair<Integer, String> pair2 = new Pair<>(2, "Banana");
        
        // Using the generic method to compare keys (Integer type)
        boolean isSameKey = Pair.compare(pair1.getKey(), pair2.getKey());
        System.out.println("Keys are the same: " + isSameKey);  
        // Outputs: Keys are the same: false
        
        // Using the generic method to compare values (String type)
        boolean isSameValue = Pair.compare(pair1.getValue(), "Apple");
        System.out.println("Values are the same: " + isSameValue);  
        // Outputs: Values are the same: true
	}
}

Output

Keys are the same: false
Values are the same: true

 

Explanation

1. Generic Types K and V: The class Pair<K, V> is defined with two generic types, K (key) and V (value). These types are used for the fields and constructors of the class.

2. Generic Method compare: Inside the Pair class, we define a static generic method compare that takes two parameters of the same type T and compares them.

This method is independent of the generic types K and V used by the class, demonstrating how generic methods can introduce their own type parameters.

This method is useful for comparing parts of pairs or any other two values of the same type provided to it.

3. Use Case: The compare method is versatile and can be used to compare any two objects, as long as they are of the same type and their type has a proper .equals() implementation. In the main method, it’s used to compare both the keys and values of Pair instances.

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review