Pinned topic ArrayList problem
Answered question This question has been answered.
Unanswered question This question has not been answered yet.
My program needs to remove multiple elements from an ArrayList. Removing the first iten works but then the elements shift and my other indexes don't match the elements I want to remove. This must be a common thing to do. Does anyone know the solution?
Updated on 2012-08-20T13:22:23Z at 2012-08-20T13:22:23Z by gr8yash
SystemAdmin 110000D4XK2768 Posts
Re: ArrayList problem2004-12-24T18:31:52ZThis is the accepted answer. This is the accepted answer.As is, ArrayList only allows for single and range removals. The shift down of elements when one is removed is a "feature"; nice most times but a problem in your situation. About the only thing I know to do, without a lot of round-about coding or reworking ArrayList, is to delete elements in reverse order. That way the shift doesn't affect lower order elements and their location remains the same.
For example, if the list had elements 1, 2, 3, 4, 5 and you wanted to delete 1 and 4, delete 4 first; now you have 1,2,3,5. Then delete 1, which is still in the original position. I know it's a pain, but it does work.
gr8yash 270001YQTB3 Posts
Re: ArrayList problem2012-08-20T13:22:23ZThis is the accepted answer. This is the accepted answer.
- SystemAdmin 110000D4XK
Java ArrayList Iterator Example for more details.