0

I am trying to create an object of a class with dynamic naming

Object1
Object2
Object3

So, I am trying to create a dynamic name for an object of the class Adder.

Adder addar[];

and I am trying to store that object in the ArrayList.

ArrayList<Adder> list= new ArrayList<Adder>();

Inside a printer method I have used below code.

addar[count] = new Adder();
addar[count].addName(theName);
addar[count].addAge(theAge);
list.add(addar[count]);

When I try to run the program i get this exception

Exception in thread "main" java.lang.NullPointerException<br/>
  at Moving.printer(Moving.java:65)
  at OrPGan.main(OrPGan.java:7)

at line

addar[count] = new Adder();

What is causing this? How can I deal with this?

Your response would be greatly appreciated.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
PickleR
  • 23
  • 3

1 Answers1

0

You need to initialize the array of Adder objects in addition to initializing each individual Adder member of that array. Try this code:

Adder addar[] = new Adder[10];
ArrayList<Adder> list= new ArrayList<Adder>();

int count = 0;

addar[count] = new Adder();
addar[count].addName(theName);
addar[count].addAge(theAge);
list.add(addar[count]);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360