Android Question [SOLVED] headache on my List

noeleon

Active Member
Licensed User
I need help.

I have a list whose contents must never change. So I create a new list and copy the contents of the original list using AddAll.

The problem is when I change the contents of the new list the original gets changed too.

What am I doing wrong? Code seems to work fine on a list of integers but not on a list of custom type.


B4X:
#Region  Project Attributes 
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName: 
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes 
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
End Sub

Sub Globals
    Dim OriginalList, PreviewList  As List
    Dim AdjustedOffset As Int
    Type cType(name As String, time As Int)
End Sub

Sub Activity_Create(FirstTime As Boolean)
    OriginalList.Initialize
    For i = 100 To 1000 Step 100
        Dim x As cType
        x.Initialize
        x.time = i
        OriginalList.Add(x)
    Next
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub activity_Click
    AdjustedOffset = AdjustedOffset + 100
    AdjustOffset(AdjustedOffset)
End Sub

Sub AdjustOffset(ms As Int)
    PreviewList.Initialize
    PreviewList.AddAll(OriginalList)
    For Each lkiiwe As cType In PreviewList
        lkiiwe.time = lkiiwe.time + ms
        Log(lkiiwe.time)
    Next
    Dim Orig1 As cType = OriginalList.Get(0)
    Log("adjusted offset: "& ms)
    Log("Orig1: "& Orig1.time)     ' THIS SHOULD NOT BE CHANGING!!!!
End Sub
 

emexes

Expert
Licensed User
I think what you are looking for is a deep copy.

https://www.b4x.com/android/forum/threads/copy-a-list-not-just-make-an-alias.12318/#post-69187

Or perhaps this:

upload_2019-9-28_12-39-56.png


My understanding is that the rules for using value/reference assignment are the same as for by-value/reference parameter passing. Simple variables are "physically" assigned/copied/passed, compound objects (arrays, classes, apparently custom types too) are assigned/copied/passed by reference, ie for each element, there is one object in memory, and it is shared between your two lists.

I get the feeling that you will have to copy your OriginalList element custom types field-by-field to newly-created custom type variables, which you then add to the PreviewList.

Btw: Nice topic heading!
 
Upvote 0

noeleon

Active Member
Licensed User
Wow! For almost 2 weeks now I've been mentally banging my head and physically pulling my nose hair because of this problem. Thank you emexes! It's finally solved.
 
Upvote 0
Top