I'm trying to write a method(using generics) which takes two parameters and swap them but parameters can be of any type - int, char, float, String etc. Following is my code -
public class SwapTest<K> {
private static void swap(K k, K v) {
K p;
System.out.println("Before swap: a = " + k + " b = " + v);
p = k;
k = v;
v = p;
System.out.println("After swap: a = " + k + " b = " + v);
}
public static void main(String[] args) {
swap(20.5, 30.3);
swap(10, 25);
swap("abc", "xyz");
}
}
But at method definition, it gives error - Cannot make static reference to non-static type
I could achieve using Object class with method definition like -
private static void swap(Object k, Object v) { ...}
but I'm trying to achieve this with generics. How can this be done?