1

I've done a lot of research but only found that java cannot pass object by reference. But, then how does System.arraycopy() change the value of an array provided.

Ritik Jain
  • 21
  • 1

3 Answers3

0

System.arraycopy() changes an array's contents, not the object/reference itself. The array you include as input parameter must be declared outside the method.

Ray
  • 3,084
  • 2
  • 19
  • 27
0

I do not know exactly what your "pass object" means. If you means call a function and pass object as parameter. Then in Java, any Object is passed in reference. This means that if you modify that object in the function called, the modification will take effect even function returns.

zchen
  • 109
  • 2
  • 7
0

System.arraycopy() changes contents of an array, not the exact array. However it's possible to write a Pointer class.

public class Pointer<T>{
    private T value;

    public Pointer(T value){
        this.value = value;
    }

    public T get(){
        return value;
    }

    public void set(T value){
        this.value = value;
    }
}

Pointer<SomeClass> pointer = new Pointer<>(theObject);

pointer.set(otherObject);
theObject = pointer.get();

Or to use "the System.arraycopy() trick":

SomeClass[] pointer = new SomeClass[]{ theObject };

pointer[0] = otherObject;
theObject = pointer[0];
Kamil Jarosz
  • 2,168
  • 2
  • 19
  • 30