Article From:https://www.cnblogs.com/quxiangjia/p/9970724.html
public class Test{
int tour;
public static void cs(Test a[]) {
        for (int i = 0; i < a.length; i++) {
            a[i]=new Test();//Here to solve the code
            a[i].tour=i;
        }
    }
 

Previously, only when the object array was used as a parameter, then Eclipse reported itException in thread “main” java.lang.NullPointerExceptionThe exception was checked later because each element of the object array has not been allocated space, so after adding the code, the method works properly.

  Summary: 1. Basic type arrays are directly allocated space to each array element after new operation, and our custom object arrays belong to reference arrays, so when used, we need to use for loop to perform new operation on each array element.   Allocate space.

            2.String type arrays are also reference arrays, but there are in the library, so Eclipse defaults to it as “basic type”. (I’ll correct here that String type array elements also need to do a new operation to have new memory space, or null references.)

Supplementary: The above solution continues to be optimized, namely

public class Test{
int tour;
public static void cs(Test a[]) {
        for (int i = 0; i < a.length; i++) {
                      a[i].tour=i;
        }
public static void main (String[] args){
Test[] c =new Test[5];
for(int i=0;i<c.length;i++)//Once the object array is created directly, a separate element for each object array passes through
c[i]=new Test();//newOperations allocate new dynamic memory space;
}
    }

 

These explanations only represent personal perception. If they do not conform to reality, they are expected to be corrected by their predecessors.

 

Leave a Reply

Your email address will not be published. Required fields are marked *