Java 中的锯齿状数组
交错数组,也称为数组数组,是一种数据结构,其中数组用于存储其他数组。交错数组的关键特征是主数组的每个元素都可以具有不同的大小,从而允许在二维结构中可变的列长度。
为了理解 Jagged 数组的概念,让我们考虑一个示例。假设我们想要存储有关学生及其各自成绩的信息。我们可以创建一个锯齿状数组来表示这个数据结构。以下是它的外观:
使用交错数组的好处是,当每个子数组中的元素数量不同时,它可以灵活地存储数据。这在列数可能发生变化的情况下特别有用,例如在处理不规则数据或稀疏矩阵时。
总体而言,锯齿状数组提供了一种灵活的方式来表示和处理数据结构,其中每个维度的大小可能会有所不同,这使它们成为某些编程场景中的强大工具。
示例 1
在上面的代码中,我们首先声明了一个 2D 锯齿状数组,该数组具有三行。但是,我们此时不指定列长度。接下来,我们将不同大小的数组分配给锯齿状数组的每一行。第一行有三个元素,第二行有两个元素,第三行有四个元素。
最后,我们使用嵌套循环来遍历并打印其元素。外部循环遍历各行,内部循环遍历每行的列。jaggedarray
文件名:JaggedArrayExample.java
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jaggedArray = new int[3][];
// Assigning different-sized arrays to the jagged array
jaggedArray[0] = new int[] { 1, 2, 3, 4 };
jaggedArray[1] = new int[] { 5, 6, 7 };
jaggedArray[2] = new int[] { 8, 9 };
// Accessing and printing the elements of the jagged array
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}
输出
1 2 3 4
5 6 7
8 9
示例 2
在上面的代码中,我们声明了一个二维锯齿状数组 jaggedArray,并使用不同年级的学生姓名对其进行初始化。第一行代表一年级学生的姓名。第二行代表二年级学生的姓名,依此类推。
然后,我们使用嵌套循环来遍历锯齿状数组并打印每个年级的学生姓名。外部循环遍历行(成绩),内部循环遍历每个年级的列(学生)。
文件名: JaggedArrayExample.java
public class JaggedArrayExample {
public static void main(String[] args) {
// Declare and initialize a 2D jagged array to store names of students in different grades
String[][] jaggedArray = {
{ "Ram", "Laxman" }, // Grade 1 students
{ "Rahul", "Gauri", "Komal" }, // Grade 2 students
{ "Ajinkya", "Virat", "Tejaswi", "Sanju" } // Grade 3 students
};
// Accessing and printing the elements of the jagged array
for (int i = 0; i < jaggedArray.length; i++) { // Iterate over the rows (grades)
System.out.print("Grade " + (i + 1) + " students: ");
for (int j = 0; j < jaggedArray[i].length; j++) { // Iterate over the columns (students) of each grade
System.out.print(jaggedArray[i][j] + " "); // Print the name of each student
}
System.out.println(); // Move to the next line after printing the names of students in a grade
}
}
}
输出
Grade 1 students: Ram Laxman
Grade 2 students: Rahul Gauri Komal
Grade 3 students: Ajinkya Virat Tejaswi Sanju
示例 3
在上面的代码中,我们有一个锯齿状数组 jaggedArray,它在每一行中存储不同的数字。第一行有三个元素,第二行有两个元素,第三行有四个元素,第四行有一个元素。然后
我们使用嵌套循环来遍历锯齿状数组并计算每行的总和。外部循环遍历各行,内部循环遍历每行的列。每行的总和是通过将该行中的所有元素相加来计算的。
文件名:JaggedArrayExample.java
public class JaggedArrayExample {
public static void main(String[] args) {
int[][] jaggedArray = {
{ 1, 2, 3 }, // First row with three elements
{ 4, 5 }, // Second row with two elements
{ 6, 7, 8, 9 }, // Third row with four elements
{ 10 } // Fourth row with one element
};
// Calculate the sum of each row and display the results
for (int i = 0; i < jaggedArray.length; i++) {
int rowSum = 0;
for (int j = 0; j < jaggedArray[i].length; j++) {
rowSum += jaggedArray[i][j];
}
System.out.println("Sum of row " + (i + 1) + ": " + rowSum);
}
}
}
输出
Sum of row 1: 6
Sum of row 2: 9
Sum of row 3: 30
Sum of row 4: 10