Author Topic: Generics Example  (Read 4486 times)

Musfiqur Rahman

  • Newbie
  • *
  • Posts: 45
    • View Profile
    • Musfiqur Rahman
Generics Example
« on: March 23, 2023, 01:19:29 PM »
Here's an example of using Java generics to create a generic method that can work with any type of object:

public class Example {
    // This method takes an array of any type of objects and prints them out
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }

    public static void main(String[] args) {
        // Creating arrays of different types of objects
        Integer[] intArray = {1, 2, 3, 4, 5};
        Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5};
        String[] stringArray = {"apple", "banana", "orange", "grape"};

        // Printing out the arrays using the generic method
        printArray(intArray);
        printArray(doubleArray);
        printArray(stringArray);
    }
}

In this example, we've defined a generic method called printArray that takes an array of any type of objects and prints them out. The method uses a type parameter T to specify the type of the objects in the array. The <T> before the return type of the method is a type parameter declaration, indicating that the method is generic and can take any type of object.

In the main method, we've created arrays of different types of objects, and then we've called the printArray method with each of these arrays. Because the printArray method is generic, it can work with any type of object, and we don't need to create separate methods for each type of object.

When we run this program, it will output:

1
2
3
4
5
1.1
2.2
3.3
4.4
5.5
apple
banana
orange
grape

As we can see, the printArray method is able to print out arrays of integers, doubles, and strings without any problems, thanks to the use of Java generics.