B4J Question Unexpected List behaviour

Josias

Member
Licensed User
Longtime User
When running the following code, the out is unexpected:

Type myType( temp As Int, str As String)

Dim Info As myType
Dim myList As List
myList.Initialize
For i = 3 To 7
Info.temp = i
Info.str = "Value : " & i
myList.Add(Info)
Next

For i = 0 To myList.Size-1
Log (myList.Get(i))
Next

The temp value and the str 'i' value will be 7 for ALL entries in the list
The expected result is that the first list entry should have a value of 3, next 4 etc
If I add 'i' to the list it functions as expected

Any ideas?
 

stevel05

Expert
Licensed User
Longtime User
B4X:
Dim myList As List
myList.Initialize
For i = 3 To 7
    Dim Info As myType
    Info.Initialize
    Info.temp = i
    Info.str = "Value : " & i
    myList.Add(Info)
Next

For i = 0 To myList.Size-1
    Log (myList.Get(i))
Next

You need to Create a new info object each iteration, otherwise you are just updating the initial one and storing that multiple times. It is also good practice to initialize the Type object, even though you don't really need to for simple types. And please use code tags when posting code.
 
Last edited:
Upvote 0

Josias

Member
Licensed User
Longtime User
THnx for the feedback. It is appreciated.
Just from a curiosity point of view, why is it that when I add the the first entry, 'i' will 3 for the first item in the list. On the second add call when I=4, it will change the value of the first item in the list as well to 4. Or is it that the list only stores a pointer to the data and not a copy of the actual data? (Seen from a 'C' language perspective)
 
Upvote 0
Top