Search code examples
javalibgdxcomparator

How to handle null compare method arguments in Comparator?


I have created an implementation of Comparator<Entity>, but when I use this comparator to sort an Array<Entity>. I will receive an java.lang.NullPointerException, because when I map the entity to a static collections which is already removed. Now my problem is I don't know what to return to skip the compare method.

public class CustomComparator implements Comparator<Entity> {

   public int compare(Entity e1, Entity e2) {
       if( e1== null || e2 == null) {
           return // don't know what to return to skip this method;
       }

       Vector2 e1Pos = Mapper.transform.get(e1).position;
       Vector2 e2Pos = Mapper.transform.get(e2).position;

   }

}

Solution

  • You can't "skip" the comparison. What would you expect the sorting code to do? You've got to provide it with a result.

    Two options are common:

    • Throw a NullPointerException to indicate that you just don't support comparing null values. That's explicitly an option in the compare documentation
    • Decide that null comes before everything else, but is equal to itself

    The latter implementation would be something like:

    public int compare(Entity e1, Entity e2) {
        if (e1 == e2) {
            return 0;
        }
        if (e1 == null) {
            return -1;
        }
        if (e2 == null) {
            return 1;
        }
        Vector2 e1Pos = Mapper.transform.get(e1).position;
        Vector2 e2Pos = Mapper.transform.get(e2).position;
        return ...;
    }