// 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
*/