Topic
  • 2 replies
  • Latest Post - ‏2012-08-20T13:22:23Z by gr8yash
SystemAdmin
SystemAdmin
2768 Posts

Pinned topic ArrayList problem

‏2004-12-23T17:18:36Z |
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
    SystemAdmin
    2768 Posts

    Re: ArrayList problem

    ‏2004-12-24T18:31:52Z  
    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
    gr8yash
    3 Posts

    Re: ArrayList problem

    ‏2012-08-20T13:22:23Z  
    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.
    If you want to remove elements from the ArrayList in a loop then you must use the Iterator. refere
    Java ArrayList Iterator Example
    for more details.