How to Create a Jagged 2D Array in Java

How do I create a jagged 2d array in Java?

In Java, a 2D array is an array of 1D array objects. Each 1D array can have different length, which means that you get jagged arrays out of the box.

For example, the following is perfectly valid Java, and prints out 3 5 3 4:

    int x[][] = {{0,1,2,3,4},{0,1,2},{0,1,2,3}};
System.out.println(x.length);
System.out.println(x[0].length);
System.out.println(x[1].length);
System.out.println(x[2].length);

Creating a 2 dimensional jagged array of undetermined size

You can make it array an instance variable and initialize it in some init method or constructor.

public class Test{
int[][] array;

public void initialize() {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
array = new int[m][n];
}

public void processArray() {
if(array != null) {
//process array
}
}
}

Combining elements in jagged 2D arrays into one new jagged 2D array (Deep Copy issue)

Flaw in your approach

You are creating a new 2D array object each iteration of your loop. Each time through, you are reassigning c, thus throwing out all of your previous work. Additionally, placing a number in both set of brackets at the same time results in each row having the same length.

Using your example, the first time through the loop, c is assigned to a 2D array with two rows, each of length three. The second time through the loop, you throw out your previous 2D array and create a new one having two rows, each of length six.

But what you need to be doing is creating a new row each time through the loop, not the entire 2D array.

Solution

First, we create a 2D array called c and specify that it has a.length rows. We don't put a value in the second bracket, because that would indicate that all of the rows are of the same length. So at this point, c does not know about row length. It just knows how many rows it can have. Keep in mind: c doesn't actually have any rows yet, just a capacity for a.length rows.

Next, we must create the rows and assign a length/capacity to them. We set up our loop to run as many times as there are rows. The current row index is denoted by i, and therefore, c[i] refers to a specific row in the 2D c array. We use new int[] to create each individual row/array, but inside the brackets, we must specify the length of the current row. For any row c[i], its length is given by the sum of the lengths of a[i] and b[i]; that is, a[i].length + b[i].length.

What we are left with is an array c that contains rows/arrays, each with a set length/capacity that matches the sum of the corresponding rows lengths in a and b.

Keep in mind that c still does not contain any integer values, only containers that are of the correct size to hold the values in a and b. As you mentioned, you already have code to populate your array with values.

int[][] c = new int[a.length][];     

for (int i = 0; i < a.length; i++) {
c[i] = new int[a[i].length + b[i].length];
}

Sequential filling of a jagged array. How does this code work?

You can add output to this code. The count variable is needed to sequentially fill the array with integers from 0 and so on.

int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
// iterate through the rows of the array
for (int i = 0; i < arr.length; i++)
// iterate through the columns of the array
for (int j = 0; j < arr[i].length; j++)
// set the array element and increment the counter
arr[i][j] = count++;

// output
for (int[] row : arr) System.out.println(Arrays.toString(row));

Output:

[0, 1, 2]
[3, 4]

Convert 2D jagged array to proper array Java

When you want to write the values to the correct indices they represent, then you can't just do full_array[i][j] = array[i][j], because this ignores the value and just simply "fills" the array, because j just increments normally.

What you actually need to do is use the value of array[i][j] as index specification:

full_array[i][array[i][j] - 1] = array[i][j];

Mind that you need to reduce 1, because your values start from "1", but array indices from "0".

Now the output is like you expect it to be:

[[1, 2, 0, 0], [1, 0, 0, 0], [0, 0, 3, 4], [0, 2, 3, 4]]


Now to some minor code improvements.

  1. ArrayList<ArrayList<Integer>> multilist = new ArrayList<ArrayList<Integer>>(); should be refactored to List<List<Integer>> multilist = new ArrayList<>();, because should declare your types as open as they could be, but as narrow as they need to be. You need a List, but you actually don't care it they are an ArrayList or for example a LinkedList. Also read Java - declaring from Interface type instead of Class.

  2. This cast multilist.add((ArrayList<Integer>) integers) is not needed. You had to added because you (correctly) declared integers as List<Integer> instead of ArrayList<Integer>, but since we fixed that in "1." you don't need it anymore.

  3. for (int i = 0; i < multilist.size(); i++) {
    System.out.println("Elements are: " + multilist.get(i));
    }

    can be replace with an enhanced-for-loop:

    for (List<Integer> integers : multilist) {
    System.out.println("Elements are: " + integers);
    }

Jagged Array & Nested For Loop in Java

Your code doesn't loop forever: it loops 12 times, because you have declared a 4x3 array - i.e. an array sized 4 where each of the elements is an array of 3 ints.

Instead, I think you want something like this:

int[][] num2d = {new int[4], new int[3]};

Adding the columns of a jagged 2D array

I think that your second while loop is making your sum too big. You should only have to iterate over the rows.

while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}


Related Topics



Leave a reply



Submit