Android Question Can anyone explain why my code has this output?

Hello, everyone, here's a code snippet that I failed to understand. I don't get why variable mylist still has access to the data of variable lst even if sub t1 is finished. Does this mean that the memory for and data of variable lst isn't released immediately after t1?
B4X:
'-------in main module-------------

sub globals
    private mylist as list
    ...
end sub

sub btton1_click
    mylist.initialize
    t1
    log(mylst.get(0)) 'The purpose of this code is to see if variable lst has been deleted after t1 ends'
end sub

sub t1
    Dim lst as list
    lst.initialize
    lst.add("abcd")
    mylst=lst   'variable mylst is a reference to lst'
end t1



'-----the output
abcd
 
Solution
This is not C. You don't need to worry about such things. The garbage collector will release the memory of objects when there are no live references to them.

Computersmith64

Well-Known Member
Licensed User
Longtime User
Because strings are immutable in B4A, your assignment is making a copy of the contents of the list, not creating a reference to the original (local) variable. Because of this, when the local variable is destroyed, the global variable you copied it to still contains the value(s) you copied to it. This doesn't apply to all types though...

This thread might explain it a bit better.

- Colin.
 
Upvote 0

emexes

Expert
Licensed User

I'm not sure this is correct. I think that the line mylist = lst is setting both mylist and lst to point to the same (one) list object, and that list object is not freed/deleted upon exiting t1 because there is still the global mylist pointing to it.

Eg after fixing and extending the OP code to:

Code:
Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Private mylist As List
End Sub

Sub Button1_Click
    '''xui.MsgboxAsync("Hello world!", "B4X")
    mylist.initialize
    Log("before t1: " & mylist)
    t1
    Log("after t1: " & mylist) 'The purpose of this code is to see if variable lst has been deleted after t1 ends'
End Sub

Sub t1
    Dim lst As List
    lst.initialize
   
    lst.add("abcd")
    Log(lst)
   
    mylist=lst   'variable mylst is a reference to lst'
   
    lst.Add("efgh")
    Log(lst)
End Sub

then the result is this:

Log output:
Logger connected to:  HMD Global Nokia C01 Plus
--------- beginning of system
--------- beginning of main
before t1: (ArrayList) []
(ArrayList) [abcd]
(ArrayList) [abcd, efgh]
after t1: (ArrayList) [abcd, efgh]
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…