Search code examples
javaarraysmultidimensional-arraydynamic-memory-allocation

How can I expand the entries of a 2d array in Java?


How can I dynamically allocate space for n entries, if I already know the number of columns of a 2d array? I wanted to know the way to doing this without using Lists but I cannot find anything. Any help?


Solution

  • Try this.

    
    int rows = 200;
    int cols = 300;
    
    int[][] mat = new int[rows][cols];
    

    You can also read in the row and col from a file, allocate your array and then continue reading the values to populate the array.

    The difficulty comes when you don't know the size of the array. So you need to first, pre allocate the array which is a guess. Then read in as much as you can and continually increase the size until you are done reading.