Rafał Developer
Rafał Developer

Reputation: 2055

Java - java.lang.NullPointerException (put data into List<>)

I would like to know why I have got this error. Have you got idea and do you know how to fix it?

Error(I get this error in put()):

Exception in thread "main" java.lang.NullPointerException
at nacs.put(nacs.put:36)
at Program.main(Program.java:69)

Program: (Main)

Nac nacs = new Nac();
nacs.put(new Intsult(1));
nacs.put(new Intsult(2));

Class:

public class Nac implement IPoraw
{
public List<IAbstrsUlt> abs;
public void put(IAbstrsUlt value)
{
abs.add(value);
}
}

Upvotes: 0

Views: 121

Answers (3)

PermGenError
PermGenError

Reputation: 46428

Variable abs is never initialized.

try this

public List<IAbstrsUlt> abs = new ArrayList<>();

Upvotes: 2

Amit Deshpande
Amit Deshpande

Reputation: 19185

Initialize list.

private List<IAbstrsUlt> abs = new ArrayList<IAbstrsUlt>();

Note: You should always try to declare your members more restrictive. Default value for Object is null. Refer Oracle tutorial to know default values.

Upvotes: 10

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

public List<IAbstrsUlt> abs;

- In the above statement you have simply declared an List Reference Variable named abs of type IAbstrsUlt, and as the Object Reference Variable has a default value of null, so it does in this case too.

- You must initialize it.

public List<IAbstrsUlt> abs = new List<IAbstrsUlt>();

Upvotes: 1

Related Questions