On the Exception of Null Pointer of Dynamically Initializing Object Type Array

After dynamically initializing the object type array, setter the array elements, and the getter has a null pointer exception

For the following code

//动态定义Student类型数组,数组长度为3
Student[] stuArrays = new Student[3];
//遍历stuArrays数组,并赋值
for(Student s : stuArrays){
    
    
	s.setName("张三")
}

NullPointException will occur when running-null pointer exception

Since the above dynamically defined object array only declares an object array, but each object in the object array is not initialized, the default value is null.

The null here is not the field in every object is null

Insert picture description here

To put it simply, if the setter and getter methods are applied to the objects of the array at this time, it is natural that a null pointer exception is reported!

Here you need to manually initialize each object

//动态定义Student类型数组,数组长度为3,并对每个对象初始化
Student[] stuArrays = new Student[3];
for(int i=0;i<stuArrays.length;i++){
    
    
    stuArrays[i]=new Student();
}

There is a point to note

  • To use for loop
  • If you use the foreach loop, there will still be a NullPointerException, because the underlying call is the Student object

After initializing each object, you can modify the member fields normally
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_48254340/article/details/108116109