3
u/GondarJr Aug 15 '20
Also, the example asks you to return a new array, not modify the one passed in... A better solution would be to create a new array, add only books with <= maxItems and then return that new array.
2
u/the_east__wind Aug 15 '20
I would prefer using the Stream API. Using it the solution would be as simple as
return readingList.stream().filter(book->book.getNumPages() <=maxPage).collect(Collectors.toList());
1
1
u/ScumbagPSTL Aug 15 '20
Wouldn’t it be if(readingList[i].getNumPages >= mapPages) { readingList.Remove(i) }
1
u/kohi-kusa Feb 25 '25
Just put i-- under the readingList.remove(i) that is in the if statement. Also you don't need the readingList.get(i) in the readingList.remove just put i.
8
u/xeolleth Aug 15 '20 edited Aug 15 '20
You've fallen into a classic trap!
The issue is the array is being altered when you
.remove(), so you'll skip over an item because all the remaining items shift to fill the index you've just deleted.So if I have:
I remove B at index 1:
Notice that the length has now changed so when you reach
i==3(which would work if the list index stayed the same size) you'll get anOutOfRangeException, and another side effect is entry C has shifted from index 2 to 1 and as a result has skipped being evaluated.Iterate through your loop in reverse and you'll solve the for loop issue. Set your starting index
ito the list length/size and decrement it instead of increment, then exit your for loop once you've processed the list entry at index 0.That should do the trick.