How to create a generic method in Java

2 Answers

0 votes
public class MyClass {
    public static <T> void printArray(T[] arr) {
        for(T element : arr) {
             System.out.printf("%s ", element);
        }
        System.out.println();
    }
    public static void main(String args[]) {
        Integer[] intArray = { 4, 8, 1, 3, 9, 4 };
        Double[] doubleArray = { 3.14, 2.15, 8.43, 9.19 };
        Character[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
     
        printArray(intArray);   
     
        printArray(doubleArray);   
     
        printArray(charArray);  
    }
}
    
    
    
    
/*
run:
    
4 8 1 3 9 4 
3.14 2.15 8.43 9.19 
a b c d e f g 
 
*/

 



answered Apr 19, 2020 by avibootz
edited Nov 14, 2023 by avibootz
0 votes
// Generic Swap Method Demonstration in Java

public class Main {

    // Generic method that swaps two elements in an array
    public static <T> void swap(T[] arr, int i, int j) {
        T temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    // Helper method to print arrays
    public static <T> void printArray(T[] arr) {
        for (T item : arr) {
            System.out.print(item + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {

        // Integer array
        Integer[] intArr = {10, 20, 30, 40};
        System.out.print("Before swap (int): ");
        printArray(intArr);
        swap(intArr, 1, 3);
        System.out.print("After swap  (int): ");
        printArray(intArr);

        System.out.println();

        // String array
        String[] strArr = {"Java", "C#", "Python", "Go"};
        System.out.print("Before swap (string): ");
        printArray(strArr);
        swap(strArr, 0, 2);
        System.out.print("After swap  (string): ");
        printArray(strArr);

        System.out.println();

        // Double array
        Double[] dblArr = {1.1, 2.2, 3.3, 4.4};
        System.out.print("Before swap (double): ");
        printArray(dblArr);
        swap(dblArr, 2, 3);
        System.out.print("After swap  (double): ");
        printArray(dblArr);
    }
}



/*
run:

Before swap (int): 10 20 30 40 
After swap  (int): 10 40 30 20 

Before swap (string): Java C# Python Go 
After swap  (string): Python C# Java Go 

Before swap (double): 1.1 2.2 3.3 4.4 
After swap  (double): 1.1 2.2 4.4 3.3 

*/

 



answered 18 hours ago by avibootz
...