Problem with assigning an array to other array in Java

前端 未结 4 569
情歌与酒
情歌与酒 2020-11-27 19:20
public class TestingArray {

    public static void main(String[] args) {

        int iCheck = 10;
        int j = iCheck;
        j = 11;
        System.err.printl         


        
相关标签:
4条回答
  • 2020-11-27 20:06

    Because arrays in Java are objects, i.e. passed by reference.

    0 讨论(0)
  • 2020-11-27 20:07

    Because you assign a reference of val1 to val2, so they both point to the same object in the memory.

    0 讨论(0)
  • 2020-11-27 20:23

    The following statement makes val2 refer to the same array as val1:

    int[] val2 = val1;
    

    If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

    int[] val2 = Arrays.copyOf(val1, val1.length);
    

    Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

    Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.

    0 讨论(0)
  • 2020-11-27 20:25

    Simply put, "val1" and "val2" are pointers to the actual array. You're assigning val2 to point to the same array as val1. Therefore, change one, and the other sees the same change. To have it truly be a copy, you'd have to clone the array instead of assigning.

    0 讨论(0)
提交回复
热议问题