Other Arrays

LucaMs

Expert
Licensed User
Longtime User
Not a question, not a bug... just a strange... fact.

B4X:
Sub Activity_Create(FirstTime As Boolean)

   Dim MyObjects(3) As clsMyClass
   MyObjects(0).Initialize(0)
   MyObjects(1).Initialize(1)
   MyObjects(2).Initialize(2)
   LogArr("MyObjects", MyObjects) ' THIS IS OK
  
   Dim arrInt(3) As Int
   arrInt(0) = 0
   arrInt(1) = 1
   arrInt(2) = 2
   LogArr("arrInt", arrInt) ' INVALID CASTING here
End Sub

Sub LogArr(ArrName As String, Arr() As Object)
   LogColor(ArrName, Colors.Red)
   For Each obj As Object In Arr
       LogColor(obj, Colors.Red)
   Next
End Sub
 

agraham

Expert
Licensed User
Longtime User
An Int is a primitive value and cannot be cast directly to an Object which is a reference type. An individual Int can appear be cast as the Java compiler will 'box' an individual primitive to create a new boxed primitive, which is a reference type, but this can cause confusion as the boxed version is a separate entity and assignments to it would not be reflected in the variable holding the original primitive.

To cast an array of a primitive value to an array of Objects the whole array would need to be recreated as an array of boxed Ints and as the compiler won't do this for efficiency reasons it throws an exception.
 
Upvote 0

Similar Threads

  • Article
Android Code Snippet Convert map to array
Replies
1
Views
1K
  • Article
Android Code Snippet Checks on arrays
Replies
3
Views
6K
Top