Android系列。对java进行排序。lang.NullPointerException
我有这个功能:
final ArrayList<Addressable> tempStoreList = new ArrayList<>();
tempStoreList.addAll(addressables);
Collections.sort(tempStoreList, new Comparator<Addressable>() {
@Override
public int compare(Addressable o1, Addressable o2) {
double distanceToO1 = 0;
double distanceToO2 = 0;
if (o1.getAddress() == null) {
return (o2.getAddress() == null) ? 0 : -1;
}
if (o2.getAddress() == null) {
return 0;
}
if (userLocation != null && o1.getAddress() != null && o2.getAddress() != null) {
distanceToO1 = GlobalUtilities.distance(userLocation, o1.getAddress().getLocation(), "K");
distanceToO2 = GlobalUtilities.distance(userLocation, o2.getAddress().getLocation(), "K");
}
if (distanceToO1 < distanceToO2) {
return -1;
} else if (distanceToO1 > distanceToO2) {
return 1;
} else {
return 0;
}
}
});
出于某种原因,我一直在以下方面获得NPE:
if (o2.getAddress() == null) {
return 0;
}
对我来说,这意味着null以某种方式被放置在数组中。以前有人遇到过这种情况吗
# 1 楼答案
是的,数组列表中可以有空元素
试试这个:
因此,如果不能保证始终拥有有效的对象,请将代码更改为
# 2 楼答案
这意味着你需要检查氧气参考。它可能是空的。在从o2得到地址之前。getAddress第一次检查o2==null