B4J Question 2 dimensional array dimension.

sorex

Expert
Licensed User
Longtime User
Hello,

Is there a way to get both sizes of a 2 dimensional array?

I can use a global variable to define the sub size but I was just wondering if it was retrievable.

B4X:
dim mda(5,3) as int

'how to get the lenght of 3?
 
You mean this?
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    
    Dim Col As Int = 5
    Dim Row As Int = 4
    Dim Matrix(Col,Row) As Int
End Sub
 
Upvote 0
if you write general function it's handy if you can retrieve both sizes.

below is an example.

usually my work grids are square but if they aren't the Y logic ain't right.
and using global variables there is kind of non logical.

B4X:
Sub printGrid(g(,) As Int)
    Dim t As String
    For y=0 To g.Length-1
        For x=0 To g.Length-1
            If x=0 Then
                t=t & g(x,y)
            Else
                t=t & "," & g(x,y)
            End If
        Next
        t=t & CRLF
    Next
    Log(t)
End Sub

I hoped that g(0).length would work but it doesn't :)
 
Upvote 0
you can solve it by making an array of lists.
But maybe there is a way to get the second dimension
 
Upvote 0
Try this:

B4X:
Dim mda(5,3) As Int
   
    Dim Result As Map = GetDimensions(mda)
    Log("Cols : " & Result.Get("Cols"))
    Log("Rows : " & Result.Get("Rows"))

B4X:
Private Sub GetDimensions(A As Object) As Map
    Dim Jo As JavaObject
    Jo.InitializeStatic("java.util.Arrays")
    Dim L As List = Jo.RunMethod("asList",Array(A))
    Dim Cols As Int = L.Size
    Dim A1() As Int = L.Get(0)
    Dim Rows As Int = A1.Length
    Return CreateMap("Cols":Cols,"Rows":Rows)
End Sub
 
Upvote 0
both methods (reflection & javaobject) work, thanks for that.

Can I see it as a serious shortcoming when you know that java (and other languages) does it out of the box with the previous mentioned mda(0).length?

I'll post it as request.
 
Upvote 0
Back
Top