[英]The value of an array changes without any command affecting it
我在以下代碼中面臨一個奇怪的問題:
public class Main {
public static void main(String args[]){
int[] c = {0};
int[] a = c;
int[] b = c;
a[0] = 1;
b[0] = 2*a[0];
System.out.println(" a " + a[0]);
}
}
這將返回“ a 2”,而不是“ a 1”,這意味着即使操作僅影響數組b,數組a的值也會更改! 有誰知道這可能來自哪里,以及如何解決?
罪魁禍首在這里:
int[] c = {0};
int[] a = c;
int[] b = c;
您認為您正在創建三個不同的數組,但實際上它們都指向同一數組c
。
System.out.println(a + "-" + b + "-" + c); //[I@1b6d3586-[I@1b6d3586-[I@1b6d3586
所有變量實際上都指向內存中的同一數組。
您所做的就是有效地創建了與聲明數組時相同的數組的2個副本:
int[] a = c;
這與寫作相同:
int* a = c;
編寫時,c與&c [0]相同,它是數組的基地址。
所以:
int[] c = {0};
int[] a = c;
int[] b = c;
a[0] = 1; // This also sets the value of c[0] and b[0] to 1
b[0] = 2*a[0]; // This is 2 * 1 = 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.