banner
指数爆炸

指数爆炸

我做了对饭 !
github
bilibili

How to modify the array in the main method within other methods?

public class Demo1 {
    public static void main(String[] args) {
        int arr[] = {2, 3, 4};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int arr[]) {
        int arr1[] = {0, 3, 4};
        arr = Arrays.copyOfRange(arr1, 0, arr1.length);
    }
}

Output: [2, 3, 4]

In this code snippet, I expect to modify the arr by calling the sort method and print the modified result. However, the output still shows the original array [2, 3, 4].

This is because in Java, when you pass an array to a method, you are actually passing the reference (memory address) of the array. Inside the sort method, when you reassign arr to point to a new array arr1, it only affects the local variable arr and does not change the original array in the main method.

Solution:#

  • Modify the array that the reference points to within the sort method
public class Demo1 {
    public static void main(String[] args) {
        int arr[] = {2, 3, 4};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int arr[]) {
        // Modify the arr array directly within the sort method
        arr[0] = 0;
        arr[1] = 3;
        arr[2] = 4;
    }
}
  • Change the return type of sort to int[], then modify the array in the main method
public class Demo1 {
    public static void main(String[] args) {
        int arr[] = {2, 3, 4};
        arr = sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static int[] sort(int arr[]) {
        int arr1[] = {0, 3, 4};
        return Arrays.copyOfRange(arr1, 0, arr1.length);
    }
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.