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() };
You’d have to do something like this:
The first line just creates an array – and an array is always filled with null references (or zero values etc). No
Polygonobjects have been created at this point, which is why you try to usepolygons[0].addPointyou’ll get aNullPointerException.If you want to populate it with references to newly created objects, you need to explicitly create those objects.