New to Java and came across this example online. The function removeZeros is supposed to remove all Integers in the ArrayList that are zero, but for some reason, it doesn't remove them if they're consecutive. I'm really confused by this, as I cannot see why it does not strictly remove all occurrences of 0 in the array. The reason is probably really obvious but I just cannot see it...
public static void main(String args[])
{
List<Integer> a = new ArrayList<Integer>();
a.add(0);
a.add(0);
a.add(4);
System.out.println(a); // prints [0 , 0 , 4]
removeZeros(a);
System.out.println(a); // prints [0 , 4] ?? why not just [4]?
}
// function to remove all zeros from an integer list
public static void removeZeros(List<Integer> nums)
{
for (int i = 0; i < nums.size(); i++)
if (nums.get(i) == 0)
nums.remove(i);
}
Any insight is appreciated.