Few days back I got an opportunity to talk to a fresher who have recently joined our company, while talking to him, he has asked me an interesting question … what is difference between this syntax ……… int[][] and int[,] ?
There is shuttle difference between the above array declaration …
The first one is known as ‘Jagged Array’ and the second one is a normal daily used two dimensional array J ( I don’t know whether there is any jargon for this type of array )
We can initialize the first one as follows …
int[][] jaggedArr = new int[4][];
jaggedArr[0] = new int[] { 0, 1, 2, 3 };
jaggedArr[1] = new int[] { 4, 5 };
jaggedArr[2] = new int[] { 6, 7, 8 };
jaggedArr[3] = new int[] { 9, 10, 11, 12, 13, 14, 15 };
if you look at the above declaration, all the array element is having a single dimension array, but the array length is different, jaggedArr[0] has an array of 4 elements, jaggedArr[1] has an array of 2 elements, jaggedArr[2] has an array of 3 elements …
But, when it comes to the second one, i.e. int[,], we have to initialize it as mentioned below,
int[,] intArr = new int[3, 4]{
{ 0,1,2,3 },
{4,5,6,7},
{8,9,10,11}
};
So, here also all the array element is having a single dimension array, but the array length exactly same as mentioned during initialization, the array contains by intArr[0], intArr[1], intArr[2] is having the same number of elements.
Now, the question is when to use a jagged array ? well, when we know beforehand that each array element will contain another array and the number of element of this array will vary for each outer array element.
For example, if we have an array of polygons, and each element(row) contains the vertices of the polygon, we can use a jagged array in this case, since each polygon( Square, Rectangle, etc ) have different number of vertices.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment