Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Gabriel Ward
20,222 Pointslooping through multidimensional array
I know that you can't use the Length property in multidimensional arrays. Instead you have to use GetLength. I'm looking for a bit more explanation as to why this is.
2 Answers
Sonya Trachsel
13,674 PointsHi Gabriel,
This is a trick to get the length of an array, be it an array of primitives or an array of objects. This allows to write a method that operates on both array types.
For example here is a method that prints the content of any type of array:
void print(Object array) { for (int i = 0; i < Array.getLength(array); i++) { System.out.println(Array.get(array, i)); } } This will work with int[] or Object[] parameters.
Otherwise you should just use the .length static field.
Seth Kroger
56,416 PointsThe length property works just fine on multidimensional arrays. You just have to remember that a multidimensional array is an array of arrays (of arrays...) so array.length is the length of the first dimension. If you want the second dimension you need the length of that row in the array.
int[][] array = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
for( int i=0; i < array.length ; i++) {
for (int j=0; j < array[i].length ; j++) {
System.out.printf(array[i][j] + " ");
}
System.out.printf("\n");
}
Gabriel Ward
20,222 PointsHi Seth,
I know you can use .length on jagged arrays, such as the one you've illustrated here. I think I'm getting a bit confused with C# where a multidimensional array is declared with int[,] array = new int[,]; And for that you can't use .length, you have to use GetLength();
Seth Kroger
56,416 PointsEven though they share a common heritage and similarities Java and C# are still different languages. That bit of C# wouldn't work in Java because arrays need a fixed length that has to be declared. For example: int[][] array = new array[4][5]; would work but new array[][]; wouldn't.