Jagged Array = mảng của mảng (int[][]). Phần tử là reference type (mảng con), khởi tạo mặc định null.
Khai báo
int[][] marks; // Chỉ khai báo, null
Khởi tạo
int[][] marks = new int[5][]; // 5 hàng, mỗi hàng null
marks[0] = new int[] { 40, 57 };
marks[1] = new int[] { 34, 55 };
// ...
Hoặc initializer:
int[][] marks = new int[][]
{
new int[] { 90, 95 },
new int[] { 89, 94 },
new int[] { 78, 87 },
new int[] { 76, 68 },
new int[] { 98, 91 }
};
Ví dụ
using System;
namespace MyApplication
{
class MyDemoClass
{
static void Main(string[] args)
{
int[][] marks = new int[][]
{
new int[] { 90, 95 },
new int[] { 89, 94 },
new int[] { 78, 87 },
new int[] { 76, 68 },
new int[] { 98, 91 }
};
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
Console.WriteLine("marks[{0}][{1}] = {2}", i, j, marks[i][j]);
}
Console.ReadKey();
}
}
}
Kết quả
marks[0][0] = 90 marks[0][1] = 95 marks[1][0] = 89 marks[1][1] = 94 marks[2][0] = 78 marks[2][1] = 87 marks[3][0] = 76 marks[3][1] = 68 marks[4][0] = 98 marks[4][1] = 91
Jagged vs Rectangular
| Đặc điểm | Jagged ([][]) | Rectangular ([,]) |
|---|---|---|
| Row length | Khác nhau được | Cùng nhau |
| Memory | Non-contiguous | Contiguous block |
| Access | marks[i][j] | marks[i,j] |
| GC | Nhiều object nhỏ | 1 object lớn |
| Performance | Cache miss nhiều hơn | Cache friendly |