Reputation: 69
I understand that x
is a jagged array in
int x[][] = {{0,1,2,3,4},{0,1,2},{0,1,2,3}};
But given an array a
like
int a[] = {10,3,47,4,8};
is a
a jagged array?
Upvotes: 1
Views: 144
Reputation: 7042
The Overall CS Answer
The term "jagged" (I've also seen "ragged") array refers to a multi-dimension array (>1) where each element is an array. Thus
int[] a = {1,2,3};
Is not a jagged array, but
int[][] a = {{1,2,3,4}, {5,6,7}};
Is. However, counterintuitively,
int[][] a = {{1,2,3,4}, {5,6,7,8}};
is also a jagged array, even though it "looks even" if you draw it out:
int[][] a = {
{1,2,3,4},
{5,6,7,8}
};
This is because other coding languages (such as c#) distinguish between multi-dimensional arrays and jagged arrays. In those languages, "jagged" is not a description of the current structure of the array in question, but what type of object it is entirely. See the difference between the two here
The Java Answer
Unlike other languages, Java only allows for single arrays of a given type. Thus the type int[][]
really is "an array of int[]
". So Java doesn't support true multi-dimensional arrays, it only has jagged arrays
Because of this, the term "jagged" array takes on a different meaning in conventional java-speak. As all arrays of dimension > 1 are truly jagged, the term "jagged" comes to mean an array of dimension > 1 whose sub arrays of differing length.Thus the following array is "jagged" because the first and second sub-arrays are of unequal length:
int[][] a = {{1,2,3,4}, {5,6,7}}
As this is equivalent to:
{
{1, 2, 3, 4}, //Length 4
{5, 6, 7} //Length 3
}
This array would also be considered jagged:
{
{1, 2, 3, 4}, //Length 4
{11, 12, 13, 14}, //Length 4
{21, 22, 23, 24}, //Length 4
{31, 32, 33, 34}, //Length 4
{5, 6, 7} //Length 3
}
Even though the following is a jagged array in the technical sense, it would not conventionally be referred to as such:
int[][] a = {
{1,2,3,4},
{5,6,7,8}
}
Similarly, because "jagged"ness requires two sub-arrays to be of unequal length, a 1-d Array can't be jagged as it has no sub-arrays to compare.
Upvotes: 4
Reputation: 201537
An array of one dimension can't be jagged, since a jagged array is an array of arrays that are of multiple lengths (as in your first example).
int a[] = {10,3,47,4,8};
is not a jagged array. The Wikipedia entry on Jagged array says (in part)
a jagged array, also known as a ragged array, is a type of multidimensional array data structure whose elements consist of one-dimensional arrays, hence it is an "array of arrays".
Upvotes: 4