Simulate passing by reference for an array reference (i.e. a reference to a reference) in Java

I was wondering, in java, is it possible, in any case, to simulate passing by reference to an array? Yes, I know, the language does not support it, but I can do it anyway. Say, for example, I want to create a method that reorders all the elements in an array. (I know this piece of code is not a good example, as there are better algorithms for this, but it is a good example of what I want to do for more complex problems).

Currently I need to make a class like this:

public static void reverse(Object[] arr) {
    Object[] tmpArr = new Object[arr.length];
    count = arr.length - 1;
    for(Object i : arr)
        tmpArr[count--] = i;
    // I would like to do arr = tmpArr, but that will only make the shallow
    // reference tmpArr, I would like to actually change the pointer they passed in
    // Not just the values in the array, so I have to do this:
    for(Object i : tmpArr)
        arr[count++] = i;
    return;
}

Yes, I know that I can just change the values ​​until I get to the middle, and that would be much more efficient, but for other, more complex purposes, is there still that I can manipulate the actual pointer?

Thanks again.

+3
5

, ?

Java , . , Java . , , .

, :

  • (ala java.util.Arrays.sort)
  • (, Throwable setStackTrace)
  • return (ala java.util.Arrays.copyOf)
+2

, , . java.util.concurrent.atomic.AtomicReference , , , , . ( ).

+1

. . ( Java , .)

   public static void reverse(Object[] arr) {
       for ( int i = 0, j = arr.length - 1;   i < j;   i++, j-- ) {
           Object temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
       }
   }
+1

Java .

, -

function referenceCheck()
{
    int[] array = new int[]{10, 20, 30};
    reassignArray(&array);
    //Now array should contain 1,2,3,4,5
}

function reassignArray(int **array)
{
    int *array = new int[] { 1, 2, 3, 4, 5};
}

Java .

, , , .

0

You want to pass a reference to an array reference. In this case, you just need to create a class to store the link and pass a link to this class or just pass an array of 1 element of the transferred type. Then you will pass the object containing the array or array, the only element of which contains the array with which you want to work.

-1
source

Source: https://habr.com/ru/post/1737634/


All Articles