How to handle comparison method arguments in Comparator?

I created an implementation Comparator<Entity>, but when I use this comparator to sort Array<Entity>. I will get java.lang.NullPointerExceptionit because when I map the object to static collections that are already deleted. Now my problem is that I do not know what to return to skip the comparison 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;

   }

}
+4
source share
2 answers

You cannot skip the comparison. What would you expect from a sort code? You must provide him with the result.

There are two options:

  • Throw NullPointerExceptionto indicate that you simply do not support comparison of values null. This is clearly an option in the documentation.compare
  • , null ,

:

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 ...;
}
+12

, , , . : " Comparable, , ". . API . , . .

+2

Source: https://habr.com/ru/post/1656440/


All Articles