Dynamic Two Dimensional Array in Java

Published by user on

In the majority of cases once a two dimensional array is created then the number of rows and columns remains the same, but sometimes you want it to be dynamic. 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.

dynamic two dimensional array java

Program to demonstrate dynamic two dimensional array

We will look at:

  1. How to create a dynamic 2d array using a List<int[]>.
  2. How to add rows to it.
  3. Print the rows, and then add some more rows.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DynamicTwoDimensionalArray {
	public static void main(String[] args) {
		List<int[]> values = new ArrayList<int[]>();
		values.add(new int[] { 88, 66, 78 });
		values.add(new int[] { 28, 58, 96 });
		values.add(new int[] { 71, 98 });
		// print data of each row
		for (int[] eachRow : values) {
			System.out.println(Arrays.toString(eachRow));
		}
		// adding new row
		values.add(new int[] { 89, 47 });
		System.out.println("After adding a new row.");
		// print data of each row
		for (int[] eachRow : values) {
			System.out.println(Arrays.toString(eachRow));
		}
	}
}

Output:

[88, 66, 78]
[28, 58, 96]
[71, 98]
After adding a new row.
[88, 66, 78]
[28, 58, 96]
[71, 98]
[89, 47]

In the above program, we started with three rows and then added one more row to it. Only rows are dynamic and not columns.

That’s all in this article. Please share if you like it.

Categories: Java