Can anyone help me with this gatting wrong output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone help me with this gatting wrong output

import java.util.*; public class Deletenode { public static void main(String args[]) { LinkedList<Integer> list = new LinkedList<>(); list.add(45); list.add(32); list.add(18); list.add(12); list.add(10); list.add(3); for (int i = 0; i < list.size(); i++) { if (list.get(i) > 15) { list.remove(i); } } System.out.println(list); } } output-->[32, 12, 10, 3] here should not be 32 then why is it on LinkedList

27th May 2022, 6:49 PM
Sahil Jadhav
1 Answer
+ 1
The problem is that you cha gr the list length while iterating over the list: – on the 1st iteration you remove 45, not the element 32 is at index 0 – on the 2nd iteration, i = 1, the list is [32, 18, 12, 10, 3]. So 18 is removed at index 1 It is not recommended to change the length of a list while iterating it.
27th May 2022, 6:56 PM
Lisa
Lisa - avatar