0

is it possible to do they following using only one for loop instead of 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
  • Here's a tip: keep your indentation consistent to make your code more readable. At first glance it appears the loops are nested. The second loop should not be indented so far out. Commented Feb 18, 2014 at 5:46

1 Answer 1

4

I think it is possible.

try this -

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);
}

In case rowIterator.hasNext() returns false, in that case list will add null value. If that is correct not according to requirement then you should ommit the null like below -

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);
    }        
}
Sign up to request clarification or add additional context in comments.

2 Comments

This does the exact same work as the original code, but there is a problem in the original and here: If rowIterator.hasNext() returns false, you are appending nulls to the end of your list. Maybe that's what you want, but it might make more sense just to stop adding to the list.
I also thought the same, and I think I should add this comment too, thanks @AnnKilzer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.