Solution to null pointer error in array

1. Problem description

Here is the object array

 LocHistory[] history = new LocHistory[list2.size()];

When assigning a value to the history object, the following error is reported

2. Reasons for error reporting

LocHistory[] history = new LocHistory[list2.size()]; Only the size of the array is given, but the instantiated object is not given at the corresponding position. The premise to obtain history [i] is that there is an object under coordinate I.

3. Solutions

Create a new object for each object reference
History [i] = new lochistory();

The specific codes are as follows:

 LocHistory[] history = new LocHistory[list2.size()];
            for (int i = 0; i < list2.size(); i++) {
             history[i] = new LocHistory();
             String PageX = list2.get(i).getPageX();
             String PageY = list2.get(i).getPageY();
                history[i].setPageX(PageX);
                history[i].setPageY(PageY);

Read More: