Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Why does putting Java arrays as an argument in a method set it outside of the method?

I am quite confused as to why my Array is being changed when I do not change the actual variable. This is an example showing how I did the exact same thing to an array and an int but got different results.

import java.util.Arrays;
public class example
{
    public static void main(String[] args)
    {
        int[] arrayInMain = {1,2,3,6,8,4};
        System.out.println("Original Value: " + Arrays.toString(arrayInMain));
        arrayMethod(arrayInMain);
        System.out.println("After Method Value: " + Arrays.toString(arrayInMain));
        int intInMain = 0;
        System.out.println("Original Value: " + intInMain);
        intMethod(intInMain);
        System.out.println("After Method Value: " + intInMain);
    }
    private static void arrayMethod(int[] array)
    {       
        int[]b = array;
        b[1] = 99;//Why does this not just set the local array? The array outside of this method changes
    }
    private static void intMethod(int i)
    {
        int j = i;
        i = 99;//This works normally with only the value of j being changed
    }
}

The output was:

Original Value: [1, 2, 3, 6, 8, 4]
After Method Value: [1, 99, 3, 6, 8, 4]
Original Value: 0
After Method Value: 0

Why is this? Am I making a silly mistake or is this just how Java arrays work?

Thank you!


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

1 Answer

0 votes
by (71.8m points)

Like @khelwood said, you are passing the reference to the array. By changing the reference, you also change the original in Java. What you can do to create an actual copy of your array you can use Arrays.copyOf()

int[] arrayCopy = Arrays.copyOf(yourArray, yourArray.length);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...