How to declare and initialize two-dimensional matrices?

Asked

Viewed 1,926 times

5

I have to save the row, column and contents of a spreadsheet. For this I created a two-dimensional matrix. My difficulty is how to initialize it? I believe the statement is no longer correct because I receive ArrayIndexOutOfBoundsException. In this situation, matrix is the appropriate data structure?

if ("Veículo".equals(cell.getStringCellValue())) {
                            String[][] referencia = new String[][];
                            for (int i = cell.getColumnIndex(); i < 4; i++) {
                                referencia[cell.getRow().getRowNum()][cell.getColumnIndex()] = cell.getStringCellValue();
                            }
                        }
  • 2

    you need to specify the size of the array in the new String[][]

1 answer

4


To declare and initialize the array correctly you need to know how many rows and how many columns it will have, and then initialize it anyway:

String[][] referencia = new String[quantidadeLinhas][quantidadecolunas];

whereas

String[][] referencia = new String[10][4];

results in

String[][] referencia = {
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null},
    {null,null,null,null}
}
  • 1

    I had forgotten that it is not a "dynamic structure", thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.