4

I need to create a list of lists in Ballerina. In java, I would simply say List<List<String>>. How do I do this in ballerina?

I have the following code.

int[][] arr = [[1,2,3], [4,5,6]];

I need to add elements to the 3rd list and it is not possible as below,

arr[3][0] = 4;
Dinu94
  • 165
  • 1
  • 12

2 Answers2

2

Ballerina has multidimensional arrays, you can do


    int[][] arr = [[1,2,3], [4,5,6]];

You can find more about them here link

In your 2nd sample code you don't have a sub array at index 3. You need to assign a empty array to index 3 and then set it's 0th element to 4.


    arr[3] = [];
    arr[3][0] = 4;
    // or
    arr[3] = [4];

Dhananjaya
  • 1,510
  • 2
  • 14
  • 19
  • 1
    I tried this and my issue was when I wanted to add a third list it didn't let me. (E.g: [[1,2,3], [4,5,6], [2,3,4]];) So I guess the number of rows is fixed after initializing? – Dinu94 Jan 11 '19 at 05:57
  • 1
    Managed to do this by using arr[3] = [4, 0]. thanks. – Dinu94 Jan 11 '19 at 06:31
  • Size of any of those component arrays are not constrained unless you explicitly constrain them. int[][2] pairArray = [[1,2,3]] fails due to constraint violation. – Dhananjaya Jan 11 '19 at 06:35
0

You can create a two dimensional array in Ballerina for this purpose. Arrays in Ballerina are mutable lists of values of dynamic length (link).

The following set of codes helped me to dynamically create a two dimensional array.

//dynamically initializing a 2D array in Ballerina v0.990.2
int[][] iarray = [];
int[] item1 = [];
int[] item2 = [];

item1[0] = 1;
item1[1] = 2;

item2[0] = 1;

iarray[0] = item1;
iarray[2] = item2;

io:println(iarray);

Output : [[1, 2], [], [1]]