java之对象数组

xiaoxiao2021-02-28  116

好长时间没有看Java,简直忘得一干二净。。。。。。好吧,言归正传,这次犯得错是对象数组元素的逐个实例化。原本以为在创建完对象数组后就完事了,元素也会自动创建,结果遍历数组后显示为null,并报空指针异常。

实例代码:

class student{

private string name;

public student(string name){this.name=name;}

public string getname(){return this.name;}}

public class test {

public static void main(string args[]){

student array[];

array=new student[3];

/*student[]array=newstudent[3];*/

array[0]=new student(”lilei”);

array[1]=new student(”cili”);

array[2]=new student(”wuxi”);

system.out.println(”对象数组元素:”);

for(int i=0;i<array.length;i++){

system.out.println(array[i] );

} 

}

上述程序的运行结果:null、null、null;由此得知,自定义对象数组,需要对数组中的每个对象元素独立进行创建,然后才可以对其赋值、引用等操作,如果没有单独对每个对象元素创建,会导致空指针异常。

即应加上:

array[0]=new student(”lilei”);

array[1]=new student(”cili”);

array[2]=new student(”wuxi”);

转载请注明原文地址: https://www.6miu.com/read-59551.html

最新回复(0)