B4J Question Array problem

PatrikCavina

Active Member
Licensed User
Longtime User
Hi to all,
I need to insert some array of object in a list.
B4X:
Sub Process_Globals
    Private fx As JFX

    Private list As List
    Private o(3) As Object
    Private a As Int  = 0

End Sub

Sub AppStart (Form1 As Form, Args() As String)
   
    list.Initialize
    start

End Sub

Sub start
   
    For i = 0 To 99
       
        For j = 0 To o.Length-1
           
            o(j) = a
            a = a + 1
           
        Next
       
        list.Add(o)
       
    Next
   
End Sub
   
End Sub
Problem is that all elements of the list are the same. I saw in debugging mode that when object 'o' changes, all the elements in list change. How i can solve the problem?
 

EnriqueGonzalez

Expert
Licensed User
Longtime User
Afet this line

B4X:
For j = 0 To o.Length-1
'Add
Dim o2 as object = o(j)
o2 = a
'And this new o2 store it
List.add(o2)

This is known as memory allocation

When you add 'o' instead of 'o2', you are storing the same memory pointer in your list again and again.

If you dim o2 inside a for, it will create a new memory pointer.
 
Upvote 0
Top