站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Arrays of Arrays - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Arrays of Arrays

Arrays can contain arrays. ArrayOfArraysDemo (in a .java source file) creates an array and uses an initializer to populate it with four sub-arrays.
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();
        }
    }
}
The output from this program is:
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
Notice that the sub-arrays are all of different lengths. The names of the sub-arrays are cartoons[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 (in a .java source file)

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();
        }
    }
}
The output of this program is:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
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.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.