Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when Creating an Array of objects [duplicate]

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?

like image 828
marjasin Avatar asked Dec 17 '09 15:12

marjasin


People also ask

What is the most likely cause of NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

What is a NullPointerException and how do I fix it?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

How do I stop NullPointerException?

How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.

When should we throw a NullPointerException?

NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference. Accessing or modifying an instance field of the object referred by a null reference.


2 Answers

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.

like image 118
Nathan Hughes Avatar answered Oct 09 '22 12:10

Nathan Hughes


ResultList[] boll = new ResultList[5]; 

creates an array of size=5, but does not create the array elements.

You have to instantiate each element.

for(int i=0; i< boll.length;i++)     boll[i] = new ResultList(); 
like image 29
chburd Avatar answered Oct 09 '22 11:10

chburd