How to fill a two Dimensional ArrayList in java with Integers?

前端 未结 8 2458
迷失自我
迷失自我 2020-12-15 01:57

I have to create a 2d array with unknown size. So I have decided to go with a 2d ArrayList the problem is I\'m not sure how to initialize such an array or store information.

8条回答
  •  我在风中等你
    2020-12-15 02:04

    Well, if you know you have 3 rows and 5 columns (as shown in your data example) you could initialize it as follows:

    int[][] a = new int[3][5]; 
    

    However, if the number of rows changes you could do something like this:

    String dataStr = "0,1,0,1,0:0,1,1,0,1:0,0,0,1,0";
    
    String[] rows = dataStr.split(":");
    
    String[] cols = rows[0].split(",");
    

    Now you can initialize:

    int[][] a = new int[rows.length][cols.length];
    

    This will accomodate changing row and col size. Might not be the most elegant approach but it should work.

提交回复
热议问题