Actually lists are dynamic structures, you don't need to pre-define their sizes as with static structures like arrays. He is a sample program directly translating the jagged array into a jagged list of lists. I tried to keep as much of the structure as possible so as to make it easier for you to understand. The code still looks kind of "array-ish" (which I actually don't like because it is somewhat unnatural), but I hope you get the idea.
package de.scrum_master.stackoverflow.q60367936;
import java.util.ArrayList;
import java.util.List;
/**
* Demonstrate 2-D jagged array/list such that first row has 1 element,
* second row has two elements and so on.
*/
class Main {
private static void jaggedArray() {
int r = 5;
// Declaring 2-D array with 5 rows
int arr[][] = new int[r][];
// Creating a 2D array such that first row has 1 element, second row has two elements and so on.
for (int i = 0; i < arr.length; i++)
arr[i] = new int[i + 1];
// Initializing array
int count = 0;
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D Jagged Array");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
private static void jaggedArrayList() {
int r = 5;
// Declaring 2-D list of lists
List<List<Integer>> arr = new ArrayList<>();
// Adding empty sub list to main list
for (int i = 0; i < r; i++)
arr.add(new ArrayList<Integer>());
// Initializing 2-D list
int count = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j <= i; j++)
arr.get(i).add(count++);
// Displaying the values of 2D Jagged list
System.out.println("Contents of 2D Jagged ArrayList");
for (List<Integer> list : arr) {
for (Integer i : list)
System.out.print(i + " ");
System.out.println();
}
}
public static void main(String[] args) {
jaggedArray();
System.out.println("\n------------------------------\n");
jaggedArrayList();
}
}
Console log:
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
------------------------------
Contents of 2D Jagged ArrayList
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
As you can see, both the array and the list variant yield identical results. Whether you use a List<List<Integer>> or a List<List<Char>> does not matter for the algorithm.