仅使用1 for循环

时间:2014-02-18 05:23:26

标签: java arraylist

是否有可能只使用一个for循环而不是2:

int index = ws.getLastRowNum() + 1;
List<AdditiveList> list=new ArrayList<>();

for(int i=1; i<index; i++){
        list.add(new AdditiveList());
}

for(AdditiveList x: list){
         Row row=null;
         if (rowIterator.hasNext())
             row=rowIterator.next();
         x.inputAdditiveData(row);
         x.outputData();
 }

1 个答案:

答案 0 :(得分:4)

我认为这是可能的。

试试这个 -

int index=ws.getLastRowNum()+1;
List<AdditiveList> list=new ArrayList<>();
for(int i=1; i<index; i++){
    AdditiveList additiveList = new AdditiveList();
    Row row = null;
    if(rowIterator.hasNext())
        row = rowIterator.next();
    additiveList.inputAdditiveData(row);
    additiveList.outputData();
    list.add(additiveList);
}

如果rowIterator.hasNext()返回false,那么列表将添加空值。如果这是正确的而不是根据要求那么你应该省略如下的空 -

for(int i=1; i<index; i++){
    if(rowIterator.hasNext()){
       Row row = rowIterator.next();
       AdditiveList additiveList = new AdditiveList();
       additiveList.inputAdditiveData(row);
       additiveList.outputData();
       list.add(additiveList);
    }        
}