我嘗試了下面的代碼,其具有稱爲data
。這一個final
實例變量在使用int[]
argument.If整型的元素[]的構造被實例化數組的更改會反映在實例變量中,並顯示在show()'s
輸出中。但是,如果將外部數組設置爲null或新的數組,則更改不會反映在show()輸出中。陣列天線的最終實例變量和重置基準
爲什麼會發生這種情況?如果外部數組由ext [0] = x更改,則更改將顯示在inst.variable中。如果將ext引用設置爲新對象,則不會發生此變化。
public class MutabilityTest {
public static void main(String[] args) {
int[] ext = new int[] {1,2,3,4,5};
FMutable xmut = new FMutable(ext);
mut.show(); //shows [1,2,3,4,5]
System.out.println("changed ext array");
ext[0] = 99;
System.out.println("ext:"+Arrays.toString(ext)); //[99,2,3,4,5]
mut.show(); //shows [99,2,3,4,5]
System.out.println("set ext array to new");
ext = new int[]{8,8,8,8}
System.out.println("ext:"+Arrays.toString(ext)); //[8,8,8,8]
mut.show();//expected [8,8,8,8] but got [99,2,3,4,5]
ext = null;
System.out.println("ext:"+Arrays.toString(ext)); //null
mut.show(); //shows same [99,2,3,4,5]
}
}
class FMutable{
private final int[] data;
public FMutable(int[] indata){
this.data = indata;
}
public void show(){
System.out.println("XMutable:"+Arrays.toString(this.data));
}
}
in java .. 對象被refrence和數據類型使用值傳遞... –