Why doesnt the arraylist print the whole list? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why doesnt the arraylist print the whole list?

All the stuff that my code does is right, but in the case 5 when I try to print the content of the arraylist this doesnt print the whole list. Why? https://code.sololearn.com/ca8a12A139A1/?ref=app

20th Mar 2021, 3:32 AM
Diego Becerril
Diego Becerril - avatar
2 Answers
+ 3
It's because you're changing the arraylist as you access and remove items from it. Inside the loop you remove the item at i which shortens the list. You then increment i and are checking against the length of the the list. This effectively skips every other item in the list. Instead get the original length of the list before the loop and use that in your comparison. Then just always get the item at the 0th index. int sz = lista.tamaño(); for (int i = 0; i < sz; i++) { System.out.println(lista.eliminaPorIndice(0)); } Note: This isn't very efficient, but it does work. You'd be better off just going through the items instead of removing them 1 at a time, so as not to be constantly resizing the arraylist.
20th Mar 2021, 3:55 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thanks man @ChaoticDawg your answer saved my butt. You´re a legend! :D
20th Mar 2021, 4:05 AM
Diego Becerril
Diego Becerril - avatar