Android Question [SOLVED] duplicate maps elements

giggetto71

Active Member
Licensed User
Longtime User
Hi,
I have a custom type defined as below and then I have a map made of several of such objects.

B4X:
 Type MyObj (Field1 As String, Field2 as string,Field3 as int) 'etc...'
dim MyMap as map
dim Elem as MyObj
....
MyMap.initialize
Elem.Inizialize
Elem.Field1 ="something"
Elem.Field2 ="something else"
....
MyMap.put(MyElemKey,Elem)
....

Now I would need to "clone" one of these elements and create one which is basically like one of them with only one field changed.

B4X:
dim MyElem as MyObj, NewElem as MyObj
MyElem.initialize
MyElem = MyMap.GetValueAt(index) 'index = one of the maps elements'

NewElem.Initialize
NewElem = MyElem
NewElem.Field3 ="something different" 'in this way new elem should have all fields equal to elem(index) but one field which is different

'now I add the NewElem to the map
MyMap.Put(NewKey,NewElem)

If I do this the newElem is actually inserted and all the fields are ok but the field3 gets changed in MyElem too.
I would like to avoid to manually set each Field in the newElem obj (in reality they are more than 30...). Is there a smart way to do that?
thanks
 
Last edited:

roumei

Active Member
Licensed User
You can use Erel's Clone sub from here: https://www.b4x.com/android/forum/t...easy-way-to-clone-objects.101838/#post-639370
It requires the RandomAccessFile library. A quick test shows that it works with your example. You have to check for your more complex case, though.

B4X:
Sub Clone(o As Object) As Object
    Dim ser As B4XSerializator
    Return ser.ConvertBytesToObject(ser.ConvertObjectToBytes(o)) ' Edited
End Sub

Sub CloneTest
   
    ' Initialize
    Dim MyMap As Map
    MyMap.Initialize
   
    ' Create Element 1
    Dim Element1 As MyObj
    Element1.Field1 = "Element 1 Field 1"
    Element1.Field2 = "Element 1 Field 2"
    Element1.Field3 = 1
    MyMap.Put("Key Element 1", Element1)
   
    ' Create Element 2 with the same fields as Element 1 and change only Field 3
    Dim Element2 As MyObj = Clone(MyMap.Get("Key Element 1"))
    Element2.Field3 = 2
    MyMap.Put("Key Element 2", Element2)
   
    ' Check
    For Each key As String In MyMap.Keys
        Dim o As MyObj = MyMap.Get(key)
        Log(o.Field1)
        Log(o.Field2)
        Log(o.Field3)
        Log("")
    Next

End Sub
 
Last edited:
Upvote 0
Top