检查列表大小时出现NullPointer异常



我得到了该语句的空指针异常。

accountList.getTrxnList((.getTrxs((.size((>0

accountList是我从外部API调用获得的帐户列表。我确信会返回一个非null的accountList值。但我对getTrxns((是否有任何值没有信心。因此,在处理之前,我会检查是否有任何Trxn,但这也会导致空指针异常。

这是我的型号

public class AccountList{
private TrxnList trxnList;
public static class TrxnList {
private List<Trxn> trxns;
public List<Trxn> getTrxns() {
return trxns;
}
}
}

有人能指出为什么这会引发nullpointer异常吗?我对此做了一些研究,所以即使trxns列表中没有项目,我也无法理解这种引发null指针异常的情况。

谢谢。

您的列表不是实例化的,只是声明的。你需要放:

private List<Trxn> trxns = new ArrayList<>(); 

您也可以捕获NullPointerException,但我同意其他评论者的观点,即通过实例化List来解决异常。

public class AccountList{
private TrxnList trxnList;
public static class TrxnList {
private List<Trxn> trxns;
public List<Trxn> getTrxns() {
try
{
return trxns;
}
catch(NullPointerException e)
{
// handle the list==null case here
// maybe instantiate it here if it's not:
trxns = new ArrayList<>();
}
}
}
}
public class AccountList{
private TrxnList trxnList;
public static class TrxnList {
private List<Trxn> trxns;
public List<Trxn> getTrxns() {
return Optional.ofNullable(trxns).orElse(new ArrayList())
}
}
}

最新更新