我不知道這裏發生了什麼。我做了一個具有成員類的簡單應用程序。瘋了:爲什麼數組在成員級別爲零
這是我的代碼,其行爲如預期。這裏沒什麼特別的。主類使用構造函數初始化成員類並調用成員方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int array[] = null;
// Init member class
subClass = new SubClass();
subClass.doSomething();
}
和會員類的代碼:
package com.example.test;
public class SubClass {
private int[] array;
public SubClass(){
if(array==null){
array = new int[10];
}
}
public void doSomething(){
if(array == null){
// We don't get here, which is good.
}
}
}
但現在我想從一個savedInstanceState傳遞成員類的陣列,例如。爲了保持這個例子簡潔而整齊,我只傳遞一個null值的數組引用。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int[] array = null;
subClass = new SubClass(array);
subClass.doSomething();
}
和會員等級:
package com.example.test;
public class SubClass {
private int[] array;
public SubClass(int[] array){
this.array = array;
// Whatever was passed, I want to make sure we have an array to work with.
if(array==null){
// Yes, it is null so init it.
array = new int[10];
// FROM HERE IT SHOULD BE AN int[10] array AND NOT NULL IN THIS CLASS
// NO MATTER WHAT THE CALLING APPLICATION DOES WITH IT'S PRIVATE
// VARIABLE (no, not parts ;))
}
}
public void doSomething(){
// and now, array should be of 10 length but it isn't!
if(array == null){
// We do get here, which is wrong!
System.out.println("array == null in doSomething");
}
}
}
如果我傳遞一個有效的數組,像數組=新INT [1],並在構造函數中忽略了什麼傳遞,只是總是初始化爲數組= new int [10],在doSomething方法中它又是一個int [1]數組!
謝謝。
問題v.1:我可能是錯的,但SubClass中的數組永遠不會在構造函數上初始化,因爲它不爲空,它是空的數組 – 2015-03-13 19:07:59