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;
}
}
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 ...;
}
To elaborate on Jon's answer, and answer Ron's question, one should always look at the spec before deciding what to do. In this case it says "Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation." See the comparator API. It elaborates on what is meant. I can't see any other reasonable solution.