user901037
user901037

Reputation:

How to instantiate polygon array in java

I thought that

 Polygon[] polygon = new Polygon[3];

would work. It runs through the 'new' line completly fine, but once it hits adding a point, it does a null pointer exeption. I add a point like so (NPEs here)-

polygon[0].addPoint(256, 417);

However, doing it like below works, but I do not want to have a potentially large number of 'new Polygon()'. Is there a way to do it like my first line of code?

Polygon[] polygon = { new Polygon(), new Polygon(), new Polygon() };

Upvotes: 1

Views: 3145

Answers (2)

Lew Bloch
Lew Bloch

Reputation: 3433

There are good tutorials on the Oracle Java site. Read them. They don't go into a lot of depth but they're a good start. There are also good articles around the Web for which it's really true that Google is your friend (GIYF). Search for "Java tutorial", "Java introduction" or something along those lines.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500615

You'd have to do something like this:

Polygon[] polygons = new Polygon[3];
for (int i = 0; i < polygons.length; i++)
{
    polygons[i] = new Polygon();
}

The first line just creates an array - and an array is always filled with null references (or zero values etc). No Polygon objects have been created at this point, which is why you try to use polygons[0].addPoint you'll get a NullPointerException.

If you want to populate it with references to newly created objects, you need to explicitly create those objects.

Upvotes: 2

Related Questions