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.Notice that the sub-arrays are all of different lengths. The names of the sub-arrays arepublic 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(); } } }cartoons[0]
,cartoons[1]
, and so on.As with arrays of objects, you must explicitly create the sub-arrays within an array. So if you don't use an initializer, you need to write code like the following, which you can find in:
ArrayOfArraysDemo2
You must specify the length of the primary array when you create the array. You can leave the length of the sub-arrays unspecified until you create them.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(); } } }
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |