如何在Comparator中处理null比较方法参数? [英] How to handle null compare method arguments in Comparator?
本文介绍了如何在Comparator中处理null比较方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了Comparator<Entity>
的实现,但是当我使用此比较器对Array<Entity>
进行排序时.我将收到一个java.lang.NullPointerException
,因为当我将该实体映射到一个已被删除的静态集合时,会出现.现在我的问题是我不知道返回什么来跳过compare方法.
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.
共有两个选项:
- Throw a
NullPointerException
to indicate that you just don't support comparingnull
values. That's explicitly an option in thecompare
documentation - Decide that
null
comes before everything else, but is equal to itself
后一种实现类似于:
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 ...;
}
这篇关于如何在Comparator中处理null比较方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文