Question Assistance required debugging an ArrayList

Snowflake

Member
Joined
Sep 16, 2014
Messages
13
Programming Experience
Beginner
I am trying to write some code to add string arrays (Sitem) into an arraylist (Slist), but for some reason all the items in the arraylist end up containing the same string array (Sitem) values.

Text File excerpt
Runner
Lake
01-04-1994
09:43
Stalk
Pool
03-04-1994
09:46

All Slist items contain the following:
Stalk
Pool
03-04-1994
09:46

Please see my code below, and thank you for any assistance.

Code:
    Private Sub ReadFile()
        Dim FR As New StreamReader("input.txt")
        Dim Sitem(3) As String
        Dim Slist As New ArrayList

        Do While FR.Peek > -1
            Sitem(0) = FR.ReadLine
            Sitem(1) = FR.ReadLine
            Sitem(2) = FR.ReadLine
            Sitem(3) = FR.ReadLine
            Slist.Add(Sitem)
        Loop
        FR.Close()
        MsgBox(0)
    End Sub
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,332
Location
Norway
Programming Experience
10+
An array is a reference type, for each iteration you are setting item values for same array object, and adding that same array object to ArrayList multiple times. Changing the array will also reflect in array item you added before, because it is the same array. Create the (new) array within the loop.

You should also use a specific type and not the ArrayList, which is basically a List(Of Object). A specific type here would be List(Of String()) which is a list of String arrays.
 
Top Bottom