Why can elements in an array change a value, but a primitive type value cannot change? (can't understand a good heading, sorry)

See code (Java):

public static int[] array(){
     int[]arr={0,1};
     changeArr(arr);
     return arr;
}
public static void changeArr(int[]arr){
    arr[0]=100;
    arr[1]=101;
}

then I print the element in arr [], I find that arr [0] turns into 100, and arr [1] goes into 101, and I know that right, since the changeArr () method changes the values.

However

public static int m(){
   int m=0;
   changeM(m);
   return m;
}
public static void changeM(int m){
   m=100;
}

why does the value of m not change? If I print m, m is still 0, it doesn't change to 100, why? why the elements in the array can change, but the primitive type m does not change?

+4
source share
3 answers

Java . , , . , , ( , ) . , :

:

arr --------> [1, 2]

:

arr --------> [1, 2]
               ^
               |
arr-copy -------

:

arr --------> [100, 101]
               ^
               |
arr-copy -------

:

arr --------> [100, 101]

, .

:

m ========  0

:

m ========= 0


m-copy ==== 0

:

m ========= 0


m-copy ==== 100

:

m ========= 0
+2

m , . arr , . arr[i] . arr = some other array, , , .

0

Java "copy-of-values".

  • (1) (int/float/long/double...), " " . 2 : . , ( ) , , orignal.

  • (2) For reference types (Object / array) means copies of their references (similar to a "pointer" to C / C ++). Now there are 2 link instances, the original in the caller and one copy in the called. Even they are two separate links (the address is different), but their contents are the same (the content is the address for the object / array). Thus, any of them is the key to access the same object / array.

Pls see my comment below:

public static int[] array(){
     int[]arr={0,1};  // arr is a reference(pointer) to [0,1]
     changeArr(arr);  // copy the reference and pass to changeArr()
     return arr;
}
public static void changeArr(int[]arr){ // Get the copy of reference, the copy also point to [0,1].
    arr[0]=100;  // Use the reference as a key to change the array [0,1]
    arr[1]=101;  // Use the reference as a key to change the array [0,1]
}

public static int m(){
   int m=0;  // m is a primitive type(int), it stays in its own address(eg. A1).
   changeM(m);  // Make a copy of m(we call it m'), the content of m' is 0, but its address(A2) is different from m. Pass m' to changeM().
   return m;
}
public static void changeM(int m){  // Get m'.
   m=100;  // No matter how to change m', will not affect m, because they are individual.
}
0
source

Source: https://habr.com/ru/post/1532957/


All Articles