Sunday, August 19, 2018

java - NullPointerException when Creating an Array of objects

Furthermore, you can prove this to yourself by adding a debug line to your class, such as:


public class ResultList {
public String name;
public Object value;
public ResultList() {
System.out.println("Creating Class ResultList");
}
}

Whenever an object is created, one of its constructors must be called (if there is no constructor, a default one is created automatically, similar to the one you already have in your class). If you only have one constructor, then the only way to create an object is to call that constructor. If the line


ResultList[] boll = new ResultList[5];

really created 5 new objects, you would see your debug line appear on the console 5 times. If it does not, you know the constructor is not being called. Notice also that the above line does not have a parameter list with open and close parentheses "()" so it is not a function call - or constructor call. Instead, we are only referring to the type. We are saying: "I need space for an array of ResultList objects, up to 5 total." After this line, all you have is empty space, not objects.


As you try out various fixes, the debug line will help confirm you are getting what you want.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...