user806410
user806410

Reputation: 41

Objects as Arrays in java

I have created array for object and now it is showing null pointer exception

attributes attrs1[]=new attributes[6];

attrs1[0].setKey1("processor");
attrs1[0].setValue1("i3");

attrs1[1].setKey1("ram");
attrs1[1].setValue1("256mb");

attrs1[2].setKey1("display");
attrs1[2].setValue1("15");

Upvotes: 3

Views: 108

Answers (3)

Abhimanyu Srivastava
Abhimanyu Srivastava

Reputation: 506

you cannot make objects of an array instead you should mak an array of objects...so you need make objects of all the array elements using a loop.....

l00p
{
attrs[i]=new attribute()
}

Upvotes: 1

Karel Petranek
Karel Petranek

Reputation: 15154

You also have to initialize the inner instances of the array:

attributes attrs1[]=new attributes[6];
for (int i = 0; i < 6; i++)
  attrs1[i] = new attributes();

Upvotes: 2

Allocating an array only makes room for the individual objects, it does not allocate them

You need to explicitly do a new for each index in your array.

Upvotes: 9

Related Questions