0

我只想从列表中获取前几个元素。但是当我这样做时,行上有一个空指针

returnList.add(returnList1.get(i))

我测试了returnList1. 它有价值观。

ArrayList<someObject> returnList1 = new ArrayList<someObject>();
ArrayList<someObject> returnList = new ArrayList<someObject>();
returnList1=bunruiSummaryService.getFromDB(param);
int j = 10;
if(returnList1.size() < j){
    j = returnList1.size();
}
for(int i = 0; i<j; i++){
    returnList.add(returnList1.get(i));
}
4

4 回答 4

0

首先,您的代码中有很多循环漏洞。

来到NPE,

要么 returnList1=bunruiSummaryService.getFromDB(param); 回归null

可能是你没有初始化returnList

returnList.add(returnList1.get(i))
于 2013-06-01T08:16:47.227 回答
0

尝试在使用它之前进行空检查并进行相应处理:

ArrayList<someObject> returnList1 = new ArrayList<someObject>();
    returnList1=bunruiSummaryService.getFromDB(param);
    if(returnList1 == null) 
    {
        System.out.println("ERROR: List is null");  
        //handle as per your need
    }

您可能还需要检查如何初始化您的 returnList。我认为那里有一些问题。

于 2013-06-01T08:19:42.920 回答
0

您为 returnList1 创建 ArrayList,然后用数据库中的数据覆盖它,但您不为 returnList 创建 ArrayList。你应该更换:

ArrayList<someObject> returnList1 = new ArrayList<someObject>();

ArrayList<someObject> returnList = new ArrayList<someObject>();
于 2013-06-01T08:20:11.563 回答
0

这段小代码问题太多了。让我告诉你我想怎么看它:

//somewhere else defined
private static final int MAX_SIZE_OF_SOME_LIST = 10; //instead of j=10, you simply have to know what the number 10 represents!

List<SomeObject> resultList = new ArrayList<someObject>();
List<SomeObject> returnList = bunruiSummaryService.getFromDB(param); //at this point, make sure to return an empty list instead of null
int maxSize = MAX_SIZE_OF_SOME_LIST;
if(returnList.size() < MAX_SIZE_OF_SOME_LIST){
    maxSize = returnList.size(); //if you ensured the returned list is not null, if the returned list is empty, you get 0 here
}
//even so
int maxSize = returnList.size() < MAX_SIZE_OF_SOME_LIST ? returnList.size() : MAX_SIZE_OF_SOME_LIST;

for(int i = 0; i<maxSize; i++){
    resultList.add(returnList.get(i));
}

//or you could use subList:
resultList.addAll(returnList.subList(0, maxSize));
于 2013-06-01T08:32:22.943 回答