PShape.getChildren() returns also elements never added, potentially resulting in NullPointerExceptions. #3347

Closed
tillnagel opened this Issue Jun 3, 2015 · 1 comment

Comments

Projects
None yet
2 participants
@tillnagel

Using a PShape group and adding other PShapes as children the internal array gets expanded when the prior length does not suffice. This may result in null elements when calling getChildren()

PShape group = createShape(GROUP);
for (int i = 0; i < 33; i++) {
  // on i > 32 (2^5) internal array gets expanded to 64 (2^6)
  group.addChild(createShape());
}

println("length: " + group.getChildren().length); // 64
println("childCount: " + group.getChildCount()); // 33

for (PShape shape : group.getChildren()) {
  // On i > 32 a NPE is thrown 
  println(shape.getVertexCount()); 
}

Currently, you have do iterate over the children with a counter.

for (int i = 0; i < group.getChildCount(); i++) {
  PShape shape = group.getChild(i);
  println(shape.getVertexCount()); 
}

Would be great, if you either make getChildren private (or such), or return only added children.

@benfry benfry closed this in 5edf335 Jun 16, 2015

@maxauthority

This comment has been minimized.

Show comment
Hide comment
@maxauthority

maxauthority Dec 1, 2015

Are you sure this is the right fix?

I've had that code which worked fine in Processing 2.x:

PShape shape = ...;
if (shape.getChildren() != null) {
    for (PShape child : shape.getChildren()) {
        // Do something with the child
    }
}

Now with Processing 3.0.1 I get:

java.lang.NullPointerException
at processing.core.PShape.crop(PShape.java:1902)
at processing.core.PShape.getChildren(PShape.java:1909)
...

I fixed it to:

PShape shape = ...;
for (int i = 0; i < shape.getChildCount(); i++) {
    // Do something with shape.getChild(i)
}

It works now, but this has an extra crop() for each iteration which I though could be avoided by calling getChildren() just once.

Are you sure this is the right fix?

I've had that code which worked fine in Processing 2.x:

PShape shape = ...;
if (shape.getChildren() != null) {
    for (PShape child : shape.getChildren()) {
        // Do something with the child
    }
}

Now with Processing 3.0.1 I get:

java.lang.NullPointerException
at processing.core.PShape.crop(PShape.java:1902)
at processing.core.PShape.getChildren(PShape.java:1909)
...

I fixed it to:

PShape shape = ...;
for (int i = 0; i < shape.getChildCount(); i++) {
    // Do something with shape.getChild(i)
}

It works now, but this has an extra crop() for each iteration which I though could be avoided by calling getChildren() just once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment