Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - Modify an array passed as a method-parameter

Suppose I have an int-array and I want to modify it. I know that I cannot assign a new array to array passed as parameter:

public static void main(String[] args)
{
    int[] temp_array = {1};
    method(temp_array);
    System.out.println(temp_array[0]); // prints 1
}
public static void method(int[] n)
{
    n = new int[]{2};
}

while I can modify it:

public static void main(String[] args)
{
    int[] temp_array = {1};
    method(temp_array);
    System.out.println(temp_array[0]); // prints 2
}
public static void method(int[] n)
{
    n[0] = 2;
}

Then, I tried to assign an arbitrary array to the array passed as parameter using clone():

public static void main(String[] args)
{
    int[] temp_array = {1};
    method(temp_array);
    System.out.println(temp_array[0]); // prints 1 ?!
}
public static void method(int[] n)
{
    int[] temp = new int[]{2};
    n = temp.clone();
}

Now, I wonder why it prints 1 in last example while I'm just copying the array with clone() which it's just copying the value not the reference. Could you please explain that for me?


EDIT: Is there a way to copy an array to object without changing the reference? I mean to make last example printing 2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your method

public static void method(int[] n)

n is another name for the array that way passed in. It points to the same place in memory as the original, which is an array of ints. If you change one of the values stored in that array, all names that point to it will see the change.

However, in the actual method

public static void method(int[] n) {
    int[] temp = new int[]{2};
    n = temp.clone();
}

You're creating a new array and then saying "the name 'n' now points at this, other array, not the one that was passed in". In effect, the name 'n' is no longer a name for the array that was passed in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...