Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

Answer from polygenelubricants on Stack Overflow
Top answer
1 of 9
46

Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

2 of 9
20

There are no multi-dimensional arrays in Java, there are, however, arrays of arrays.

Just make an array of however large you want, then for each element make another array however large you want that one to be.

int array[][];

array = new int[10][];

array[0] = new int[9];
array[1] = new int[8];
array[2] = new int[7];
array[3] = new int[6];
array[4] = new int[5];
array[5] = new int[4];
array[6] = new int[3];
array[7] = new int[2];
array[8] = new int[1];
array[9] = new int[0];

Alternatively:

List<Integer>[] array;

array = new List<Integer>[10];

// of you can do "new ArrayList<Integer>(the desired size);" for all of the following
array[0] = new ArrayList<Integer>();
array[1] = new ArrayList<Integer>();
array[2] = new ArrayList<Integer>();
array[3] = new ArrayList<Integer>();
array[4] = new ArrayList<Integer>();
array[5] = new ArrayList<Integer>();
array[6] = new ArrayList<Integer>();
array[7] = new ArrayList<Integer>();
array[8] = new ArrayList<Integer>();
array[9] = new ArrayList<Integer>();
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ how to create a dynamic 2d array in java
How to create dynamic 2d array in Java with example - CodeSpeedy
November 1, 2018 - Learn how to create dynamic 2d array in Java. Java tutorial on dynamic 2d array with an easy example of multidimentional array.
Discussions

How to create a dynamic 2D Array in java - Stack Overflow
I am reading Arrays in Java. I want to dynamically create a 2D array in java. I know I've to use Arraylist but I don't know how to actually write the elements to location. I come from C language More on stackoverflow.com
๐ŸŒ stackoverflow.com
help with multidimensional dynamic array
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/javahelp
5
1
August 8, 2022
list - How to create Dynamic Two Dimensional Array [JAVA] - Stack Overflow
How can I make the column of teh array dynamic so that no matter how large the value of lastValue increases it runs. ... An array of ArrayList... but since Java doesn't allow array of generic (you can create non-generic ArrayList[], but there will be warning about type safety), so ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 8, 2013
How to make dynamic 2d array in Java? - Stack Overflow
An array is always fixed. To resize it, you need to reallocate it. If you want something dynamic, use a java.util container like List. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ How-to-create-a-dynamic-2D-array-in-Java
How to create a dynamic 2D array in Java?
February 24, 2020 - If you wish to create a dynamic 2d array in Java without using List. And only create a dynamic 2d array in Java with normal array then click the below link You can achieve the same using List.
๐ŸŒ
Devcubicle
devcubicle.com โ€บ dynamic-two-dimensional-array-java
Dynamic Two Dimensional Array in Java - DevCubicle By Cloud Tech
April 12, 2020 - Dynamic two dimensional array in Java is used to have varying numbers of rows where user can add or remove rows on demand. It is implemented using a combination of List and int[]. As the list can grow and shrink hence the 2d array becomes dynamic.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 43648806 โ€บ how-to-create-a-dynamic-2d-array-in-java
How to create a dynamic 2D Array in java - Stack Overflow
int rows = 3, columns = 4; ArrayList<Integer> Arr1; ArrayList<ArrayList<Integer>> Arr2 = new ArrayList<>(); for (int i = 0; i < rows; i++) { Arr1 = new ArrayList<>(); for (int j = 0; j < columns; j++) { Arr1.add(j); } Arr2.add(Arr1); } System.out.println(Arr2);
๐ŸŒ
Flowerbrackets
flowerbrackets.com โ€บ create-dynamic-2d-array-in-java
Flowerbrackets
February 8, 2021 - We cannot provide a description for this page right now
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ help with multidimensional dynamic array
r/javahelp on Reddit: help with multidimensional dynamic array
August 8, 2022 -

hello, i'm trying to implement a 3-dimensional array where the innermost array needs to be dynamic and hold a specific class type (ill call it foo)

my first thought was to make a 2d array of ArrayList like this

ArrayList<ClassType>[][] 3dArray;

and then in the constructor have

this.3dArray= New ArrayList[noOfRows][noOfColumns]

however whenever i try to to add an object like this

this.3dArray[rowIndex][colIndex].add(nameOfObject)

it gives me a NullPointerException.

Could someone help me fix this or help me find an alternative, solution, ive been stuck for hours. Tthanks

Top answer
1 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 3
1
Array entries are initialised to their default values for their type. For reference-types this is null. So after the new ArrayList[...][...] the array of arrays is full of null values, not references to ArrayLists. You could subsequently fill each array cell with a reference to a new ArrayList. for (int i = 0; i < this.3dArray.length; i++) { ArrayList[] row = this.3dArray[i]; for (int j = 0; j < row.length; j++) { row[j] = new ArrayList(); } } However mixing a generic type and arrays here does rub up against one of Java's rougher edges, that you're declaring raw-types and losing the compile-time protections of Java Generics. I'd aim to encapsulate the storage such that users of the data-structure can still use type-safe access.
Find elsewhere
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ how-to-create-dynamic-two-dimensional-array-in-java
How to Create a Dynamic Two-Dimensional Array in Java: Fixed Columns with Dynamically Changing Rows โ€” javaspring.net
By combining ArrayList (for dynamic rows) and 1D arrays (for fixed columns), you can create flexible 2D structures in Java that handle dynamic data growth while maintaining consistent column counts.
Top answer
1 of 4
2

This isn't all that easy.

You can certainly represent your grid as a List<List<Cell>>.

 public Cell getCell(int x, int y) {
       return grid.get(x).get(y);
 }

However that doesn't give you a free pass to assign to any old number:

  List<String> list = new ArrayList<>();
  list.set(5,"Hello");

... will throw an IndexOutOfBounds exception too.

You can list.add(string) as many times as you like, and each time the list will grow. But you can't set() beyond its current size.

However if you know you want a cell object for every grid position, and you know that every time it grows it will grow by one, write your algorithm to use add() not set(), and this structure will work well.


Alternatively, as you suggest, a HashMap<Coordinates, Cell> might suit your needs.

You'll need a suitable Coordinates class, with a working hashCode() and equals() implementation. Then you could do:

   Map<Coordinates, Cell> grid = new HashMap<>();
   grid.put(new Coordinates(80, 100), new Cell());

This would work especially well if you want a "grid" that's sparsely populated but effectively unbounded.

There are plenty more approaches - including implementing your own array-reallocating algorithm (after all, that's what's inside an ArrayList -- find and study its source code, if you're curious).


You should probably also step back and ask why and when you need to change the size of the grid after initialising it. A fixed-size array of fixed-size arrays is a simple solution, and worth sticking with if it works most of the time. If the size only changes occasionally, maybe you'd be better off just creating a new grid and copying the old values into it whenever that happens.

  public void setCell(int x, int y, Cell cell) {
     if(x >= this.grid.length || y >= this.grid[0].length) {
          Cell[][] newGrid = createEmptyGrid(x,y);
          copyCells(this.grid,newGrid);
          this.grid = newGrid;
     }
     this.grid[x][y] = cell;
  }

createEmptyGrid() here needs to make a decision about the new size -- just big enough to accommodate [x][y]? Or bigger just-in-case? The right thing to do depends on your broader requirements.

2 of 4
1

You could use ArrayList, but to insert at any index without worrying about going out of bounds, you'd want to use nested Map with a special method for insertion or retrieval.

Map<Integer, Map<Integer, Cell>> grid = new HashMap<Integer, Map<Integer, Cell>>();

for (int x = 0; x <= COLS_NUM; x++) {
    Map inner = new HashMap<Integer, Cell>();
    for (int y = 0; y < ROWS_NUM; y++) {
        inner.put(y, new Cell());
    }
    grid.put(x, inner);
}

Now you could create a method to set cells int the grid with any indices like this:

 public void setCell(Map<Integer, Map<Integer, Cell>> grid, Cell newCell, int x, int y) {
    if (grid.containsKey(x)) {
        grid.get(x).put(y, newCell);
    } else {
        grid.put(x, (new HashMap<Integer, Cell>().put(y, newCell)));
    }
}

And a method for retrieving a cell:

     public Cell getCell(Map<Integer, Map<Integer, Cell>> grid, int x, int y) {
     try {
         Cell found = grid.get(x).get(y);
         return found;
     } catch (NullPointerException npe) {
         return null;
     }
 }

To make this useful, you'd want to create a custom class that manages these maps and the insertion / retrieval methods for you, along with other functions useful to your application.

Here's a simpler option using lists. As mentioned above, this won't let you avoid the possibility of getting an IndexOutOfBoundsException.

int ROWS_NUM = (int) canvas.getHeight() / rectangleSize;
int COLS_NUM = (int) canvas.getWidth() / rectangleSize;

List<List<Cell>> array = new ArrayList<List<Cell>>();

for (int x = 0; x < COLS_NUM; x++) {
    List inner = new ArrayList<Cell>();
    for (int y = 0; y < ROWS_NUM; y++) {
        inner.add(new Cell());
    }
    array.add(inner);
}

You can still access specific cells (the equivalent of array[x][y] in the array this way:

// Find equivalent of arr[2][3]
Cell found = array.get(2).get(3);

However, because you specified that you want to be able to access cells with any index without getting an out of bounds exception, you could choose to implement it with Maps.

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ 2d-array-in-java-two-dimensional-and-nested-arrays
2D Array in Java โ€“ Two-Dimensional and Nested Arrays
August 10, 2022 - To create a two dimensional array in Java, you have to specify the data type of items to be stored in the array, followed by two square brackets and the name of the array.
๐ŸŒ
Oldsaintpatricks
oldsaintpatricks.com โ€บ western-australia โ€บ how-to-create-a-dynamic-2d-array-in-java.php
How to create a dynamic 2d array in java
Dynamic Arrays YouTube Design a ... inserted or removed. However, it is possible to implement a dynamic array by allocating a new array and copying the contents from the old array to the new one.......
๐ŸŒ
Reddit
reddit.com โ€บ r/developersindia โ€บ is there any better way to create 2d dynamic array in java??
r/developersIndia on Reddit: is there any better way to create 2d dynamic array in java??
December 11, 2025 -

Dear those who code in java

is this how you make 2d matrix??
If Yes, c++ is far more simple than java.

List<List<Integer>> dp= new ArrayList<>();         
for(int i = 0;i < n;i++){             
List<Integer> temp = new ArrayList<Integer>();
  for(int j = 0;j < w+1;j++){ 
    temp.add(0);             
  }             
  dp.add(temp);         
}

or am I missing here something???
I am learning Java just for job switch
generally I do DSA in C++.

๐ŸŒ
Cach3
tutorialspoint.com.cach3.com โ€บ How-to-create-a-dynamic-2D-array-in-Java.html
How to create a dynamic 2D array in Java - Tutorials Point
February 6, 2018 - How to create a dynamic 2D array in Java - If you wish to create a dynamic 2d array in Java without using List And only create a dynamic 2d array in Java with normal array then click the below linkYou can achieve the same using List See the below program You can have any number of r...
Top answer
1 of 3
8

Use collections to do this. For example:

List<List<Integer>> dynamic2D = new ArrayList<List<Integer>>();

dynamic2D.add(new ArrayList<Integer>());
dynamic2D.add(new ArrayList<Integer>());
dynamic2D.add(new ArrayList<Integer>());

dynamic2D.get(0).add(5);
dynamic2D.get(0).add(6);
dynamic2D.get(0).add(7);

System.out.println(dynamic2D.get(0).get(0)); // 5
System.out.println(dynamic2D.get(0).get(1)); // 6
System.out.println(dynamic2D.get(0).get(2)); // 7
2 of 3
4

Here's one option to consider to keep your 2D array fast for processing. It starts with a fixed size array of int[][] and grows only as necessary:

public class DynamicMatrix2D {
    private int[][] matrix = new int[5][5];

    public void set(int x, int y, int value) {
        if (x >= matrix.length) {
            int[][] tmp = matrix;
            matrix = new int[x + 1][];
            System.arraycopy(tmp, 0, matrix, 0, tmp.length);
            for (int i = x; i < x + 1; i++) {
                matrix[i] = new int[y];
            }
        }

        if (y >= matrix[x].length) {
            int[] tmp = matrix[x];
            matrix[x] = new int[y + 1];
            System.arraycopy(tmp, 0, matrix[x], 0, tmp.length);
        }

        matrix[x][y] = value;
    }

    public int get(int x, int y) {
        return x >= matrix.length || y >= matrix[x].length ? 0 : matrix[x][y];
    }

    public static void main(String[] args) {
        DynamicMatrix2D matrix2d = new DynamicMatrix2D();

        matrix2d.set(1, 1, 1);     // set (1, 1) to 1
        matrix2d.set(10, 10, 2);   // set (10, 10) to 2
        matrix2d.set(100, 100, 3); // set (100, 100) to 3

        System.out.println(matrix2d.get(1, 1));     // outputs 1
        System.out.println(matrix2d.get(10, 10));   // outputs 2
        System.out.println(matrix2d.get(100, 100)); // outputs 3 
    }
}
๐ŸŒ
Javatpoint
javatpoint.com โ€บ dynamic-array-in-java
Dynamic Array in Java - Javatpoint
Dynamic Array in Java - Dynamic Array in Java with Delimiter with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
๐ŸŒ
YouTube
youtube.com โ€บ naresh i technologies
Program on Multidimensional Array with Dynamic Values by using user Specified size in Java? - YouTube
Core Java Tutorial | Mr.Ramachandra** For Online Training Registration: https://goo.gl/r6kJbB โ–บ Call: +91-8179191999๐Ÿ’ก Also WatchC Language Tutorials: https...
Published ย  April 9, 2018
Views ย  1K