一開始自定義了一個學生類,類里面有幾個屬性。因為有很多個學生,所以想將這個類聲明成數組使用,但是當我通過不同的下標給數組里不同對象賦值的時候一直報空指針異常
一開始代碼是這樣的
package _4_9_test;
public class EightTwoTest {
public static class Test{
String name;
int num;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test[] = new Test[2];
test[0].name = "張珊";
test[0].num = 1;
test[1].name = "李四";
test[1].num = 2;
System.out.println(test[0].name+" "+test[0].num);
System.out.println(test[1].name+" "+test[1].num);
}
}
看了文檔后發現**數組的創建不會給數組成員分配內存** 也就是說
Test test[] = new Test[2];
是沒有地方可以存數據的。
只有每個成員進行聲明后才會給這個成員分配內存
test[0] = new Test();
改良后的代碼是這樣的
package _4_9_test;
public class EightTwoTest {
public static class Test{
String name;
int num;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test[] = new Test[2];
test[0] = new Test();
test[0].name = "張珊";
test[0].num = 1;
test[1] = new Test();
test[1].name = "李四";
test[1].num = 2;
System.out.println(test[0].name+" "+test[0].num);
System.out.println(test[1].name+" "+test[1].num);
}
}