Книга: C# 2008 Programmer

Arrays of Arrays: Jagged Arrays

Arrays of Arrays: Jagged Arrays

An array's elements can also contain arrays. An array of arrays is known as a jagged array. Consider the following statements:

Point[][] lines = new Point[5][];
lines[0] = new Point[4];
lines[1] = new Point[15];
lines[2] = new Point[7];
lines[3] = ...
lines[4] = ...

Here, lines is a jagged array. It has five elements and each element is a Point array. The first element is an array containing four elements, the second contains 15 elements, and so on.

The Point class represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensional plane.

You can use the array initializer to initialize the individual array within the lines array, like this:

Point[][] lines = new Point[3][];
lines[0] = new Point[] {
 new Point(2, 3), new Point(4, 5)
}; //---2 points in lines[0]---
lines[1] = new Point[] {
 new Point(2, 3), new Point(4, 5), new Point(6, 9)
}; //---3 points in lines[1]----
lines[2] = new Point[] {
 new Point(2, 3)
}; //---1 point in lines[2]---

To access the individual Point objects in the lines array, you first specify which Point array you want to access, followed by the index for the elements in the Point array, like this:

//---get the first point in lines[0]---
Point ptA = lines[0][0]; //----(2,3)
//---get the third point in lines[1]---
Point ptB = lines[1][2]; //---(6,9)---

A jagged array can also contain multidimensional arrays. For example, the following declaration declares nums to be a jagged array with each element pointing to a two-dimensional array:

int[][,] nums = new int[][,] {
 new int[,] {{ 1, 2 }, { 3, 4 }},
 new int[,] {{ 5, 6 }, { 7, 8 }}
};

To access an individual element within the jagged array, you can use the following statements:

Console.WriteLine(nums[0][0, 0]); //---1---
Console.WriteLine(nums[0][0, 1]); //---2---
Console.WriteLine(nums[0][1, 0]); //---3---
Console.WriteLine(nums[0][1, 1]); //---4---
Console.WriteLine(nums[1][0, 0]); //---5---
Console.WriteLine(nums[1][0, 1]); //---6---
Console.WriteLine(nums[1][1, 0]); //---7---
Console.WriteLine(nums[1][1, 1]); //---8---

Used on a jagged array, the Length property of the Array abstract base class returns the number of arrays contained in the jagged array:

Console.WriteLine(nums.Length); //---2---

Оглавление книги


Генерация: 1.942. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз