1
\$\begingroup\$

I am using libGDX - Ashley as entity-system framework. My problem is I don't know how do I avoid having a java.lang.NullPointerException when using Comparator<Entity> entity comparison. There is a situation where Entity is removed from the engine, but the Comparator is still continuing. Now how do I skip the comparing if one of the nearby is null?

@Override
public int compare(Entity nearby1, Entity nearby2) {
    Vector2 ownerPos = Mapper.transform.get(owner).position;
    Vector2 nearbyPos1 = Mapper.transform.get(nearby1).position; // possible null
    Vector2 nearbyPos2 = Mapper.transform.get(nearby2).position; // possible null
    return ...
}

When I sort the Array<Entity> for example, using my custom comparator, it returns an error because one of the entity is null or one of the component entity is null. I don't know what to return to make the comparison skip.

boolean skip = ownerPos == null || nearbyPos1 == null || nearbyPos2 == null;

if(skip) {
   return ??? 
}

I'm thinking of using try-catch statement to skip the sorting. But is this performance safe?

try {
   array.sort(comparator);
} catch(Exception e) {

}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I would say this responsibility should be located within the comparator. In other words if one is null and the other isn't the compare should return as -1 and if both are null it should return 0 (you might think to return -1 but this would violate the reflexivity requirement).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .