Java Reference
In-Depth Information
// Print all elements. One row at one line
System.out.println(raggedArr[0][0] + "\t" + raggedArr[0][1]);
System.out.println(raggedArr[1][0]);
System.out.println(raggedArr[2][0] + "\t" + raggedArr[2][1] + "\t" + raggedArr[2][2]);
}
}
1 2
3
4 5 6
■
Java supports an array of arrays, which can be used to achieve functionalities provided by a multi-dimensional
array. Multi-dimensional arrays are widely used in scientific and engineering applications. If you are using arrays in
your business application program that have more than two dimensions, you may need to reconsider the choice of
multi-dimensional arrays as the choice for your data structure.
Tip
Accessing Elements of a Multi-Dimensional Array
Typically, a multi-dimensional array is populated using nested
for
loops. The number of
for
loops used to populate
a multi-dimensional array equals the number of dimensions in the array. For example, two
for
loops are used to
populate a two-dimensional array. Typically, a loop is used to access the elements of a multi-dimensional array.
Listing 15-12 illustrates how to populate and access elements of a two-dimensional array.
Listing 15-12.
Accessing Elements of a Multi-dimensional Array
// MDAccess.java
package com.jdojo.array;
public class MDAccess {
public static void main(String[] args){
int[][] ra = new int[3][];
ra[0] = new int[2];
ra[1] = new int[1];
ra[2] = new int[3];
// Populate the ragged array using for loops
for(int i = 0; i < ra.length; i++) {
for(int j = 0; j < ra[i].length; j++){
ra[i][j] = i + j;
}
}
// Print the array using for loops
for(int i = 0; i < ra.length; i++) {
for (int j = 0; j < ra[i].length; j++){
System.out.print(ra[i][j] + "\t");
}