I have used a lot of C++ and I am quite confused with the way Java works :
if I have a class
public class MyClass{
private int[] myVariable;
...
public int[] getVar(){
return myVariable;
}
}
and then I want to use my variable elsewhere :
public static void main(String[] args){
MyClass myObject = new MyClass();
...
int[] temp = myObject.getvariable();
// use of temp
...
}
is temp a copy or a reference of myVariable ?
How do you get a copy / a reference to it ?
Answer
There is only one int[]
in your example. There is no copying at all. What is returned by the method getVar
is a reference to the object.
After the line
int[] temp = myObject.getvariable();
both temp
and myVariable
are references to the same object. You can test this by doing e.g. temp[0] = 9;
. The change will be visible in both places.
If you want to copy an array, you can use one of array.clone()
, Arrays.copyOf(array, array.length)
or System.arraycopy(...)
but none of these are used in your example.
No comments:
Post a Comment