Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating pass by reference for an array reference (i.e. a reference to a reference) in Java

I was wondering, in java, is it possible to in anyway, simulate pass by reference for an array? Yes, I know the language doesn't support it, but is there anyway I can do it. Say, for example, I want to create a method that reverses the order of all the elements in an array. (I know that this code snippet isn't the best example, as there is a better algorithms to do this, but this is a good example of the type of thing 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 could just swap the values until I get to the middle, and it would be much more efficient, but for other, more complex purposes, is there anyway that I can manipulate the actual pointer?

Again, thank you.

like image 640
Leif Andersen Avatar asked Feb 13 '26 18:02

Leif Andersen


2 Answers

is there anyway that I can manipulate the actual pointer?

Java does not pass by reference, so you can't directly manipulate the original pointer. As you've found out, Java passes everything by value. You can't pass a reference to an array object, and expect a method to modify the original reference to point to another array object.

You can, of course:

  • Modify elements of the referred array object (ala java.util.Arrays.sort)
  • Pass a reference to an object with a settable field (e.g. Throwable has a setStackTrace)
  • return the new reference instead (ala java.util.Arrays.copyOf)
like image 135
polygenelubricants Avatar answered Feb 16 '26 09:02

polygenelubricants


Well, you can explicitly pass an object that contains a reference. java.util.concurrent.atomic.AtomicReference is ready out of the box, although it does come with volatile semantics that you probably don't want. Some people use single element arrays to returns values from anonymous inner classes (although that doesn't seem a great idea to me).

like image 22
Tom Hawtin - tackline Avatar answered Feb 16 '26 08:02

Tom Hawtin - tackline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!