Explaining Lists

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub Swap (xx As Int, yy As Int)
No. x points to an int object with the value 3. 3 is an immutable object.
Like all other cases, a copy of the pointer is assigned to the xx parameter.

No matter what will happen inside Swap it cannot affect the pointer stored in x which will always point to the object 3.

The output will always be:
3
4

If we want to create a Swap sub then we must use mutable objects:
B4X:
Type IntHolder (Value As Int)

Dim x As IntHolder = CreateIntHolder(3)
Dim y As IntHolder = CreateIntHolder(4)
Swap(x, y)
Log(x.Value) '4

Sub Swap (xx As IntHolder, yy As IntHolder)
 Dim t as Int = xx.Value
 xx.Value = yy.Value
 yy.Value = t
End Sub

Another example:
B4X:
Dim x() As Int = Array As Int(3)
Dim y() As Int = Array As Int(4)
Swap(x, y)
Log(x(0)) '4

Sub Swap (xx() As Int, yy() As Int)
 Dim t As Int = xx(0)
 xx(0) = yy(0)
 yy(0) = t
End Sub

Note that x and y point the same two objects all the time. We modify these objects internal values.
 
Top