Mảng nhiều chiều trong Java
Mảng nhiều chiều trong Java là mảng của mảng, cho phép lưu trữ dữ liệu theo nhiều chiều khác nhau. Phổ biến nhất là mảng hai chiều (ma trận) và mảng ba chiều.
1. Khai báo và khởi tạo mảng nhiều chiều
Khai báo mảng hai chiều
// Khai báo mảng hai chiều số nguyên
int[][] matrix;
// Khai báo mảng hai chiều chuỗi
String[][] table;
// Khai báo mảng hai chiều số thực
double[][] grid;
Khởi tạo mảng hai chiều
// Khởi tạo với kích thước
int[][] matrix = new int[3][4];
// Khởi tạo với giá trị
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Khởi tạo mảng răng cưa
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[3];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
2. Truy cập phần tử mảng nhiều chiều
Truy cập trực tiếp
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Truy cập phần tử tại hàng 1, cột 2
System.out.println(matrix[1][2]); // In: 6
// Truy cập phần tử cuối cùng
System.out.println(matrix[matrix.length - 1][matrix[0].length - 1]); // In: 9
Duyệt mảng hai chiều
// Sử dụng vòng lặp for
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// Sử dụng vòng lặp for-each
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
3. Các thao tác cơ bản
Tìm phần tử lớn nhất
public class MatrixOperations {
public static int findMax(int[][] matrix) {
int max = matrix[0][0];
for (int[] row : matrix) {
for (int element : row) {
if (element > max) {
max = element;
}
}
}
return max;
}
}
Tính tổng các phần tử
public class MatrixOperations {
public static int calculateSum(int[][] matrix) {
int sum = 0;
for (int[] row : matrix) {
for (int element : row) {
sum += element;
}
}
return sum;
}
}
Tìm vị trí phần tử
public class MatrixOperations {
public static int[] findElement(int[][] matrix, int target) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
return new int[]{i, j};
}
}
}
return new int[]{-1, -1}; // Không tìm thấy
}
}
4. Các phép toán ma trận
Cộng hai ma trận
public class MatrixOperations {
public static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int rows = matrix1.length;
int cols = matrix1[0].length;
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}
}
Nhân hai ma trận
public class MatrixOperations {
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int cols2 = matrix2[0].length;
int[][] result = new int[rows1][cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
}
Chuyển vị ma trận
public class MatrixOperations {
public static int[][] transpose(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[][] result = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
}
5. Ví dụ thực tế
Quản lý bảng điểm
public class GradeTable {
private double[][] grades;
public GradeTable(int students, int subjects) {
grades = new double[students][subjects];
}
public void addGrade(int student, int subject, double grade) {
if (student >= 0 && student < grades.length &&
subject >= 0 && subject < grades[0].length) {
grades[student][subject] = grade;
}
}
public double getStudentAverage(int student) {
double sum = 0;
for (double grade : grades[student]) {
sum += grade;
}
return sum / grades[student].length;
}
public double getSubjectAverage(int subject) {
double sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i][subject];
}
return sum / grades.length;
}
}
Xử lý ảnh
public class ImageProcessor {
private int[][] pixels;
public ImageProcessor(int width, int height) {
pixels = new int[height][width];
}
public void setPixel(int x, int y, int value) {
if (x >= 0 && x < pixels[0].length &&
y >= 0 && y < pixels.length) {
pixels[y][x] = value;
}
}
public void invert() {
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels[i].length; j++) {
pixels[i][j] = 255 - pixels[i][j];
}
}
}
public void rotate90Degrees() {
int[][] rotated = new int[pixels[0].length][pixels.length];
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels[i].length; j++) {
rotated[j][pixels.length - 1 - i] = pixels[i][j];
}
}
pixels = rotated;
}
}
6. Best Practices
-
Kiểm tra kích thước mảng
// Không nên
int[][] matrix = new int[3][4];
matrix[3][4] = 10; // ArrayIndexOutOfBoundsException
// Nên
if (row >= 0 && row < matrix.length &&
col >= 0 && col < matrix[0].length) {
matrix[row][col] = 10;
} -
Xử lý mảng răng cưa
// Không nên
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
// Có thể gây lỗi với mảng răng cưa
}
}
// Nên
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
// An toàn với mảng răng cưa
}
} -
Tối ưu hóa vòng lặp
// Không nên
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
// Truy cập matrix[i].length nhiều lần
}
}
// Nên
for (int i = 0; i < matrix.length; i++) {
int rowLength = matrix[i].length;
for (int j = 0; j < rowLength; j++) {
// Truy cập rowLength đã lưu
}
}
7. Lỗi thường gặp
-
ArrayIndexOutOfBoundsException
int[][] matrix = new int[3][4];
matrix[3][4] = 10; // Lỗi: chỉ số nằm ngoài giới hạn -
NullPointerException
int[][] matrix;
System.out.println(matrix.length); // Lỗi: mảng chưa được khởi tạo -
ArrayStoreException
Object[][] matrix = new Integer[3][3];
matrix[0][0] = "Hello"; // Lỗi: không thể lưu String vào mảng Integer