0

I'm trying to make a general function that takes in an array of Unknown type and flips it. It doesn't return anything and should pass a reference to the array to the function.

I've tried to use Varargs:

public static <Unknown> void reverseArray(Unknown... a){
  Unknown t;
  for(int i=0;i<a.length/2;i++){
    t = a[i];
    a[i] = a[a.length - i - 1];
    a[a.length - i - 1] = t;
  }
}

But that doesn't work for primtives because java doesn't seem to pass in a reference to an array I've tried Object[]

public static void reverseArray(Object[] a){
  Object t;
  for(int i=0;i<a.length/2;i++){
    t = a[i];
    a[i] = a[a.length - i - 1];
    a[a.length - i - 1] = t;
  }
}

But when when I pass it int[] java says it is not applicable for the arguments (int[])

Same thing with generics:

public static <Unknown> void reverseArray(Unknown[] a){
  Unknown t;
  for(int i=0;i<a.length/2;i++){
    t = a[i];
    a[i] = a[a.length - i - 1];
    a[a.length - i - 1] = t;
  }
}
Zyansheep
  • 168
  • 2
  • 11
  • Instead of primitives, you would need to use the class version of the primitives (`Integer` instead of `int`) if you wish to go this route I think. – Tim Hunter Jul 25 '19 at 22:15
  • 1
    https://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types have a look at this answer as it can propably help you on why you cant do that – Michael Michailidis Jul 25 '19 at 22:16

1 Answers1

0

You can't do it. You have to have a separate method for each primitive type you want to support.

Take a look at the Java API for Arrays.toString() to see all the methods. Same for copyOf and for sort too, as well as others.

And even for Generic types, the common method must be something that can support all types. The previously sited examples are some. But you couldn't have a generic method that added two numbers because for a type T, the compiler would not know if T supported a particular operation.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • WHAT?!? Why is Java made this way? it seems like the compiler could do this easily... – Zyansheep Jul 25 '19 at 23:24
  • @Zyansheep Generics don't accept primitive types but use autoboxing to get the wrapper class. This doesn't work with Arrays but you can look into autoboxing, maybe you find a solution to your problem. –  Jul 25 '19 at 23:52