简体   繁体   中英

How to prevent the value of an array from changing

In my program, I am declaring a static int 2D array and setting it equal to some values. In a different method, I create a local variable and assign it to the 2D array I created. I make some changes to the local variable, however I don't want my initial values in my 2D array to change. The reason I am using static is because I am using a static main method and I figured all other methods and variables had to be static as well.

Here's a simple layout of what I am doing

public static int[][] myArray = {{1,2},{3,4}};

public static void main(String args[]){
    doSomething();
}

public static void doSomething(){
    int[][] newArray = myArray;

    //do Something to newArray

}

I do not want the values of myArray to change is there a way to handle this? Do I have to get rid of a static variable within a static method?

You will have to create deep copy of your array. You can do it manually or use System.arraycopy() to suit your needs.

Arrays are mutable and so you need to use System.arraycopy to make defensive copies. Make the array private and call a public method which hands a copy is the way to prevent mistakes of bugs by sharing a reference when you must not.

深度复制原始数组并保留这两个数组之一(仅更改其中之一)

尝试:

int[][] newArray = Arrays.copyOf(myArray, myArray.length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM