Why is the following Java codes output 523 instead of 52 imp
Why is the following Java code\'s output [5,2,3] instead of [5,2]?
import java.util.*;
public class Temp {
public static void main(String[] args){
List <Integer>list = new ArrayList<Integer>();
list.add(5);
list.add(3);
list.add(1, 2);
list.add(3);
list.add(list.size()-1,3);
int count=0;
while(count<list.size()){
if(list.get(count)==3){
list.remove(count);
}
count++;
}
System.out.println(list);
}
}
Solution
Lets take it step by step
list.add(5); => list -> |5|
list.add(3); => list -> |5|3|
list.add(1, 2); => add 2 at index 1 (currently 3 is at index 1) => list -> |5|2|3|
list.add(3); => list |5|2|3|3|
list.add(list.size()-1,3); (add 3 at end) => list -> |5|2|3|3|3|
So list is 5->2->3->3->3
Lets walk through while loop
final remaining list [5,2,3].
![Why is the following Java code\'s output [5,2,3] instead of [5,2]? import java.util.*; public class Temp { public static void main(String[] args){ List <Inte Why is the following Java code\'s output [5,2,3] instead of [5,2]? import java.util.*; public class Temp { public static void main(String[] args){ List <Inte](/WebImages/35/why-is-the-following-java-codes-output-523-instead-of-52-imp-1102518-1761582867-0.webp)