如何处理比较器中的空比较方法参数?
How to handle null compare method arguments in Comparator?
我已经创建了 Comparator<Entity>
的实现,但是当我使用这个比较器对 Array<Entity>
进行排序时。我将收到 java.lang.NullPointerException
,因为当我将实体映射到已删除的静态集合时。现在我的问题是我不知道如何return 来跳过比较方法。
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;
}
}
你不能"skip"比较。您希望排序代码做什么?你必须提供一个结果。
两个选项很常见:
- 抛出一个
NullPointerException
表示您只是不支持比较 null
值。这是 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 ...;
}
为了详细说明 Jon 的回答并回答 Ron 的问题,在决定做什么之前应该始终查看规范。在这种情况下,它表示 "Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation." 请参见 the comparator API。它详细说明了它的意思。我看不到任何其他合理的解决方案。
我已经创建了 Comparator<Entity>
的实现,但是当我使用这个比较器对 Array<Entity>
进行排序时。我将收到 java.lang.NullPointerException
,因为当我将实体映射到已删除的静态集合时。现在我的问题是我不知道如何return 来跳过比较方法。
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;
}
}
你不能"skip"比较。您希望排序代码做什么?你必须提供一个结果。
两个选项很常见:
- 抛出一个
NullPointerException
表示您只是不支持比较null
值。这是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 ...;
}
为了详细说明 Jon 的回答并回答 Ron 的问题,在决定做什么之前应该始终查看规范。在这种情况下,它表示 "Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation." 请参见 the comparator API。它详细说明了它的意思。我看不到任何其他合理的解决方案。