我已经创建了一个实现Comparator<Entity>
,但是当我使用这个比较器对一个Array<Entity>
。我将收到一个java.lang.NullPointerException
,因为当我将实体映射到已删除的静态集合时。现在我的问题是我不知道要返回什么来跳过比较方法。
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;
}
}
你不能“跳过”比较。您希望排序代码做什么?你必须向它提供一个结果。
常见的有两种选择:
- Throw a
NullPointerException
表明你只是不支持比较null
价值观。这明确是一个选项compare http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-文档
- 决定
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 ...;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)