锯齿状数组(Jagged Array、交错数组),也称为数组的数组,是一种用一个 数组存储其他数组的数据结构。锯齿状数组的关键特征是主数组的每个元素可以具有不同的大小,从而允许二维结构中的可变列长度。
为了理解锯齿状数组的概念,让我们考虑一个例子。假设我们要存储有关学生及其各自成绩的信息。我们可以创建一个锯齿状数组来表示这个数据结构。
使用锯齿数组的好处是,当每个子数组中的元素数量不同时,可以灵活地存储数据。在处理不规则数据或稀疏矩阵等列数可能不同的情况下,这一点尤其有用。
总之,锯齿数组提供了一种灵活的方式来表示和处理各维度大小可能不同的数据结构,使其成为某些编程场景中的有力工具。
示例 1
在上面的代码中,我们首先声明了一个有三行的二维锯齿数组 jagged Array。但此时我们并没有指定列的长度。接下来,我们为锯齿数组的每一行分配不同大小的数组。第一行有三个元素,第二行有两个元素,第三行有四个元素。
最后,我们使用嵌套循环遍历锯齿数组并打印其元素。外循环遍历行,内循环遍历每一行的列。
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();
}
}
}
|
输出
示例 2
在上面的代码中,我们声明了一个二维锯齿数组 jaggedArray,并用不同年级的学生姓名对其进行了初始化。第一行代表一年级学生的姓名。第二行代表二年级的学生姓名,以此类推。
然后,我们使用嵌套循环遍历锯齿数组,并打印出每个年级的学生姓名。外循环遍历行(年级),内循环遍历每个年级的列(学生)。
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,每行存储不同的数字。第一行有三个元素,第二行有两个元素,第三行有四个元素,第四行有一个元素。那么
我们使用嵌套循环遍历锯齿数组并计算每一行的总和。外循环遍历行,内循环遍历每一行的列。每一行的总和是通过将该行中的所有元素相加计算得出的。
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
|