Java 检查NullPointerException原因
我有一个我试图排序的某个类的ArrayList,但是在排序过程中我得到了一个NullPointerException。 我用try-catch包装了我的命令,以便找到数组中导致异常的元素。 我如何检查捕获物以找出哪个是有问题的元素 代码如下:Java 检查NullPointerException原因,java,nullpointerexception,try-catch,Java,Nullpointerexception,Try Catch,我有一个我试图排序的某个类的ArrayList,但是在排序过程中我得到了一个NullPointerException。 我用try-catch包装了我的命令,以便找到数组中导致异常的元素。 我如何检查捕获物以找出哪个是有问题的元素 代码如下: List<SingleMeasurementValuePoint> sortedList = new ArrayList<SingleMeasurementValuePoint>(deviceMeasurementPoints);
List<SingleMeasurementValuePoint> sortedList = new ArrayList<SingleMeasurementValuePoint>(deviceMeasurementPoints);
try {
Collections.sort(sortedList, new TimeAndComponentSort());
} catch (Exception e) {
System.out.println();
}
List sortedList=新阵列列表(设备测量点);
试一试{
Collections.sort(sortedList,new TimeAndComponentSort());
}捕获(例外e){
System.out.println();
}
比较器内的代码,即TimeAndComponentSort为:
public class TimeAndComponentSort implements Comparator<SingleMeasurementValuePoint> {
@Override
public int compare(SingleMeasurementValuePoint point1, SingleMeasurementValuePoint point2) {
int val = point1.compareTo(point2);
if (val == 0) {
return point1.getComponentId().compareTo(point2.getComponentId());
}
else {
return val;
}
}
}
公共类TimeAndComponentSort实现了Comparator{
@凌驾
公共整数比较(SingleMeasurementValuePoint点1,SingleMeasurementValuePoint点2){
int val=点1。比较(点2);
如果(val==0){
返回point1.getComponentId().compareTo(point2.getComponentId());
}
否则{
返回val;
}
}
}
我认为您无法通过查看堆栈跟踪来确定列表中的哪个元素是null
。如果您的列表中有null
元素,最简单的解决方法可能是修复比较器来处理null
。此外,您还可以使用比较器
记录空值
。基本上,类似于
@Override
public int compare(SingleMeasurementValuePoint point1,
SingleMeasurementValuePoint point2) {
if (point1 == null && point2 == null) {
System.out.println("null point1 and point2");
return 0;
} else if (point1 == null) {
System.out.println("null point1");
return -1;
} else if (point2 == null) {
System.out.println("null point2");
return 1;
}
int val = point1.compareTo(point2);
if (val == 0) {
return point1.getComponentId().compareTo(
point2.getComponentId());
} else {
return val;
}
}
这仍然不能告诉您原始索引中的哪个元素是null
。如果这是您真正需要的,那么您可以编写一个方法来返回第一个null
(或-1
)的索引,如
为什么不使用调试器呢?您可以将代码发布到comparator-TimeAndComponentSort中。我使用调试器,并站在catch中。如何检测ArrayList中4500个元素中的哪一个是导致异常的原因?如何在排序之前循环列表以找出空值?为什么不执行e.printStackTrace()?
public static <T> int findFirstNull(List<T> al) {
for (int i = 0, len = al.size(); i < len; i++) {
if (al.get(i) == null) {
return i;
}
}
return -1;
}
} catch (Exception e) {
// System.out.println();
e.printStackTrace();
}