Results 1 to 3 of 3

Thread: deleting from array list

  1. #1

    Thread Starter
    Member
    Join Date
    Jun 2006
    Posts
    61

    deleting from array list

    Hi there,
    I have this loop to delete elements from an arraylist
    VB Code:
    1. For i = 0 To myarraylist.count - 1
    2.             If some_statement Then
    3.                 myarraylist.removeat(i)
    4.             End If
    5.         Next
    Is there any risk of having index out of range, as the arraylist gets smaller??
    Basicaly the question is if the compiler sets the number of loops at the beggining or checks the myarraylist.count - 1 after every loop...Thanks

  2. #2
    Frenzied Member
    Join Date
    Oct 2005
    Posts
    1,286

    Re: deleting from array list

    Hi,
    start at the end of the array, and loop 'backwards'

    Pete

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: deleting from array list

    You will definitely go out of range unless you do as Pete suggested. If you remove even a single item, then the loop will run past the end of the array. The MyArrayList.Count expression is evaluated the first time only, so it doesn't shrink as the arraylist shrinks.

    To loop the other way, start with X = MyArrayList.Count-1 to 0 Step -1
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width