Friday, August 23, 2019

java - NullPointerException when Creating an Array of objects




I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.



public class ResultList {

public String name;
public Object value;
}




public class Test {
public static void main(String[] args){
ResultList[] boll = new ResultList[5];

boll[0].name = "iiii";
}
}


Why am I getting this exception and how can I fix it?


Answer



You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add



boll[0] = new ResultList();



before the line where you set boll[0].name.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...