To create a three-dimensional list in Java, you can use nested ArrayLists where each inner ArrayList represents a 2D plane within the 3D space.
In this example,
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<ArrayList<ArrayList<Integer>>> matrix3D = new ArrayList<>();
for (int i = 0; i < 3; i++) {
ArrayList<ArrayList<Integer>> plane = new ArrayList<>();
for (int j = 0; j < 3; j++) {
ArrayList<Integer> row = new ArrayList<>();
for (int k = 0; k < 3; k++) {
row.add(i + j + k);
}
plane.add(row);
}
matrix3D.add(plane);
}
System.out.println(matrix3D);
}
}
[[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[2, 3, 4], [3, 4, 5], [4, 5, 6]]]
In this example,
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<ArrayList<ArrayList<String>>> matrix3D = new ArrayList<>();
for (int i = 0; i < 2; i++) {
ArrayList<ArrayList<String>> plane = new ArrayList<>();
for (int j = 0; j < 2; j++) {
ArrayList<String> row = new ArrayList<>();
for (int k = 0; k < 2; k++) {
row.add("(" + i + ", " + j + ", " + k + ")");
}
plane.add(row);
}
matrix3D.add(plane);
}
System.out.println(matrix3D);
}
}
[[[(0, 0, 0), (0, 0, 1)], [(0, 1, 0), (0, 1, 1)]], [[(1, 0, 0), (1, 0, 1)], [(1, 1, 0), (1, 1, 1)]]]
In this tutorial, we learned How to create a Three Dimensional List in Java language with well detailed examples.