To create a Two-Dimensional List in Java, you can use the ArrayList class and initialize it with ArrayLists to represent rows and columns.
In this example,
matrix
to represent the 2D list.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<String>> matrix = new ArrayList<>();
for (int i = 0; i < 3; i++) {
matrix.add(new ArrayList<>());
for (int j = 0; j < 3; j++) {
matrix.get(i).add("Element " + i + j);
}
}
System.out.println(matrix);
}
}
[[Element 00, Element 01, Element 02], [Element 10, Element 11, Element 12], [Element 20, Element 21, Element 22]]
In this example,
matrix
to represent the 2D list.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<Integer>> matrix = new ArrayList<>();
for (int i = 0; i < 3; i++) {
matrix.add(new ArrayList<>());
for (int j = 0; j < 3; j++) {
matrix.get(i).add(i * 3 + j);
}
}
System.out.println(matrix);
}
}
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
In this tutorial, we learned How to create a Two Dimensional List in Java language with well detailed examples.