Looping through ArrayList to remove elements
I'm creating a binsort program and I ran into a problem. I created a ArrayList bucket and asked the user to input values. Let's say it has elements [1, 2, 3, 4, 5, 6, 7] and I'm using a for loop to remove it.
Code :
for(int i = 0; i <= bucket.size(); i++)
{
System.out.println(bucket.remove(i);
}
So to my logic, it is suppose to loop starting from 0. As it loops, as long as i is less than or equal to the size of the bucket, it'll increase by 1. As that is happening, it's suppose to remove the element at that position. It does remove it but, when I print that out, it comes out as...
1
3
5
7
2
6
4
I don't understand why would it print out like that. Also, if a user inputted an even number of elements, it would return "Index out of Bounds Exception". So just wondering why is this happening to my for loop. Any help would be appreciated!
Re: Looping through ArrayList to remove elements
Hello and welcome to the forums.
I think we may need to see a bit more of your code..
Re: Looping through ArrayList to remove elements
Consider how the loop is working - write out what exactly is happening during the loop...remove element at index 0, 1, etc...what does the array look like after each removal? How else could you loop? Are there API methods to accomplish this?
Re: Looping through ArrayList to remove elements
thank you for the responses but i figured it out.
what i was doing wrong was as i was looping through the array, i was indeed removing the element at position i but that also changed the size of my array. Which in the end, when i increases, the array size decreases. therefore, when i = 0 it removes element at position 0 which is 1 in this case, and decreases the size of the array by 1 which in this case would change from size 7 to size 6. Now when it removes element at position 1, position 1 of the array is 3 since we decreased the size of the array.