Copy a list, not just make an alias

wdegler

Active Member
Licensed User
Longtime User
I have a list containing user-defined types of values. I wish to make a copy of it and make changes to it without changing the original list.
Here is a trival sample of my problem:

Sub Globals
Type AType(A As Int,B As Int)
End Sub

Sub Activity_Create(FirstTime As Boolean)
Dim I As Short
Dim Lst1,Lst2 As List
Dim Typ As AType

Lst1.Initialize
Lst2.Initialize
Typ.Initialize
Typ.A=1: Typ.B=2 'add to Lst1
Lst1.Add(Typ)
For I=0 To Lst1.Size-1 'copy to Lst2 (Lst2=Lst1 just makes an alias)
Lst2.Add(Lst1.get(I))
Next
Dim Type As AType
Typ.Initialize
Typ=Lst2.Get(0)
Typ.B=3 'this changes Lst1 too!
End Sub

My extraordinarily simple question:
How can I create a new list as an independent copy as another?
 

wdegler

Active Member
Licensed User
Longtime User
Typo in my sample above.

'Dim Type as AType' should be 'Dim Typ as AType' and in my local sample, it is.
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Both lists are referencing the same AType item. You need to create a new AType item as well as a new list.
 
Upvote 0

wdegler

Active Member
Licensed User
Longtime User
Creating a new instance of Typ?

Thank you for your response.
Doesn't the code

Dim Typ As AType
Typ.Initialize

following the For loop create a new Typ?
 
Upvote 0

wdegler

Active Member
Licensed User
Longtime User
My amended question

I think I see what you are saying but I do not know a solution.

My question is really

How can I make a copy of a list and freely change it without affecting the original list?
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
It depends on what the list contains. If they are primitive types then a shallow copy such as you have done between Lst1 and Lst2 is sufficient. If the contents of the list to be copied are objects then you need to do a deep copy and clone those objects otherwise you are only copying references to existing objects. So for each of your AType instances you need to Dim another AType and copy the fields from one to another, and if those fields themselves contain object references you may need to clone them as well, and so on, depending upon what you are trying to achieve.
 
Upvote 0

wdegler

Active Member
Licensed User
Longtime User
Thank you for your help.

Thank you for your help.
I find that can create a copy by copying embedded primitives only. This works.
 
Upvote 0
Top