copying an object, not just a reference?

Dave O

Well-Known Member
Licensed User
Longtime User
Hi there,

Here's a pretty basic question about objects for the OO types out there:

How do I copy an object to another object?

For example, I'd like to copy object A to object B, but still maintain them as separate data.

As I understand it, when I do this with the two objects:

B = A

...B now points to the same object as A (i.e. they're both references to the same data instance).

What I want is to *copy* A to B, then be able to change B without affecting A - like what would happen if I was dealing with primitive variables.

Is there an easy way to do this, or do I have to write a copy function for each type of object I'm working with?

Thanks for any help!
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can use RandomAccessFile.WriteObject / ReadObject: (untested code)
B4X:
Sub CopyObject(Obj As Object) As Object
 Dim raf As RandomAccessFile
 raf.Initialize(File.DirInternalCache, "1.dat", false)
 raf.WriteObject(Obj, True, 0)
 Dim newObj As Object
 newObj = raf.ReadObject(0)
 raf.Close
 Return newObj
End Sub

You can keep the temp file open and make raf variable a global variable.
 
Upvote 0

Vader

Well-Known Member
Licensed User
Longtime User
Last edited:
Upvote 0

DavideV

Active Member
Licensed User
Longtime User
You can use RandomAccessFile.WriteObject / ReadObject: (untested code)
B4X:
Sub CopyObject(Obj As Object) As Object
Dim raf As RandomAccessFile
raf.Initialize(File.DirInternalCache, "1.dat", false)
raf.WriteObject(Obj, True, 0)
Dim newObj As Object
newObj = raf.ReadObject(0)
raf.Close
Return newObj
End Sub

You can keep the temp file open and make raf variable a global variable.

Thx Erel you saved my time :)
 
Upvote 0

wonder

Expert
Licensed User
Longtime User
Hi!

Is this, to date, the best way to copy an object?
I'd like to copy an array of objects, say 512.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is better to use B4XSerializator:
B4X:
Sub CopyObject(o As Object) As Object
   Dim s As B4XSerializator
   Return s.ConvertBytesToObject(s.ConvertObjectToBytes(o))
End Sub

Note that not all types are supported. Supported types are: primitives, strings, lists, maps, arrays of objects or bytes, custom types and any combination of those (a map that holds arrays of custom types).
 
Upvote 0
Top