Why my function accept a Primitive Type?

I wrote this code, and strangely it’s work in Processing for an unknown reason.

void setup() {
  int [] arr = {0,1,2,3}; // that's work, but normaly must fail
  // Integer [] arr = {0,1,2,3}; // this one work but it's normal
  printArray(arr);
  printArray(reverse(arr));
}

<T> T [] reverse(T [] arr) {
  for(int i = 0 ; i < arr.length / 2; i++) {
    T buf = arr[i];
    arr[i] = arr[arr.length - i - 1];
    arr[arr.length - i - 1] = buf;
  }
  return arr;
}

This code don’t work like expected

import rope.utils.R_Utils.Ru;
import rope.core.Rope;

void setup() {
  int [] arr = {0,1,2,3};
  printArray(arr);
  printArray(Ru.reverse(arr)); // KO,  don't work but the code is the same
}

console return

The method reverse(T[]) in the type R_Utils.Ru is not applicable for the arguments (int[])

So when I push my code in my library, unfortunately the code don’t work like expected, because
https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html and the code is exactly the same.

I post the question on java - How deal between primitive type and class of same family, in diamond <T> context? - Stack Overflow All the answers say: is it’s not possible.
So why that’s work in Processing ? I’m sure there is no miracle, but maybe there is a simple answer, who know it ? I’m very interesting, to apply it after in my library.

Hi @Stanlepunk,

You assumption for the first example is wrong, as it isn’t use your reverse function at all…

Comment out your reverse function in the first example and it will still work, because it is calling this …

Cheers
— mnse

PS: Diamond operator, resp. Generics not meant to work with primitive types.

(Read, especially at Chapter 6.)

5 Likes

Hi

//import rope.utils.R_Utils.Ru;
//import rope.core.Rope;

void setup() {
  int [] arr = {0,1,2,3};

arr = reverse(arr);
  printArray(arr);
 // printArray(Ru.reverse(arr)); // KO,  don't work but the code is the same
}

Hahahaha, wonderful. I don’t know Processing have this function. I understand now why that’s work :slight_smile: thx for pointing that!!!

Now I fix it, by adding a function overwriting in my Library. Now my function is faster than Processing. I must find a time to make a pull request to implement in Processing 4 !!!

/**
* reverse function faster than Processing
* may be when I've the possibility I push this one on Processing
*/
import rope.utils.R_Utils.Ru;
import rope.core.Rope;

int num = 30_000_000;

void setup() {
 // PVector [] arr = new PVector[num];
  String [] arr = new String[num]; 
  // int Rope faster x3.5
  // float Rope faster x3.5
  // Integer Rope faster x3.5
  // String Rope faster x1.1
  // PVector Rope faster x3.5
  for(int i = 0 ; i < arr.length ; i++) {
    // arr[i] = i;
    arr[i] = ""+i;
    // arr[i] = new PVector(i,i);
  }

  float start = millis();
  reverse(arr);
  println("P5",millis() - start);
  
  start = millis();
  Ru.reverse(arr); 
  println("Rope",millis() - start);
}
1 Like