0

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?

Alpha
  • 13,320
  • 27
  • 96
  • 163
  • The static methods need their own generic parameter. I refer you to [this duplicate](https://stackoverflow.com/questions/936377/static-method-in-a-generic-class) used to close this question. – Hovercraft Full Of Eels May 27 '17 at 02:17
  • You won't be able to use generics for any of the primitives, e.g. `int`, `float`, arrays. – ack May 27 '17 at 02:17
  • 1
    Just so you know, you're swap method does nothing. Khan's is pass by value so it is impossible to write a method to do a swap like this. – puhlen May 27 '17 at 02:19

0 Answers0