Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Arrays can contain arrays.ArrayOfArraysDemo
creates an array and uses an initializer to populate it with four sub-arrays.The output from this program is:public class ArrayOfArraysDemo { public static void main(String[] args) { String[][] cartoons = { { "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" }, { "Rubbles", "Barney", "Betty", "Bam Bam" }, { "Jetsons", "George", "Jane", "Elroy", "Judy", "Rosie", "Astro" }, { "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" } }; for (int i = 0; i < cartoons.length; i++) { System.out.print(cartoons[i][0] + ": "); for (int j = 1; j < cartoons[i].length; j++) { System.out.print(cartoons[i][j] + " "); } System.out.println(); } } }Notice that the sub-arrays are all of different lengths. The names of the sub-arrays areFlintstones: Fred Wilma Pebbles Dino Rubbles: Barney Betty Bam Bam Jetsons: George Jane Elroy Judy Rosie Astro Scooby Doo Gang: Scooby Doo Shaggy Velma Fred Daphnecartoons[0]
,cartoons[1]
, and so on.As with arrays of objects, you must explicitly create the subarrays within an array. So if you don't use an initializer, you need to write code as in the following program, called
ArrayOfArraysDemo2
The output of this program is:public class ArrayOfArraysDemo2 { public static void main(String[] args) { int[][] aMatrix = new int[4][]; //populate matrix for (int i = 0; i < aMatrix.length; i++) { aMatrix[i] = new int[5]; //create sub-array for (int j = 0; j < aMatrix[i].length; j++) { aMatrix[i][j] = i + j; } } //print matrix for (int i = 0; i < aMatrix.length; i++) { for (int j = 0; j < aMatrix[i].length; j++) { System.out.print(aMatrix[i][j] + " "); } System.out.println(); } } }You must specify the length of an array when you create it. For an array that contains subarrays, you specify the length of the primary array when you create it but don't have to specify the length of any of the subarrays until you create them.0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.