# Java多維陣列

``````int[][] table;
``````

``````table = new int[3][2];
``````

``````table[0][1] = 32;
``````

``````table[2][0] = 1;
``````

``````table = new int[3][];
``````

``````table[0] = new int[2]; // Create two  columns  for row 1
table[1] = new int[2]; // Create two  columns  for row 2
table[2] = new int[2]; // Create two  columns  for row 3
``````

Java可以為每行建立一個具有不同列數的二維陣列。這樣的陣列稱為粗糙陣列。

``````public class Main {
public static void main(String[] args) {
// Create a two-dimensional array of 3 rows
int[][] raggedArray = new int[3][];

// Add 2 columns to the first row
raggedArray[0] = new int[2];

// Add 1 column to the second row
raggedArray[1] = new int[1];

// Add 3 columns to the third row
raggedArray[2] = new int[3];

// Assign values to all elements of raggedArr
raggedArray[0][0] = 1;
raggedArray[0][1] = 2;
raggedArray[1][0] = 3;
raggedArray[2][0] = 4;
raggedArray[2][1] = 5;
raggedArray[2][2] = 6;

// Print all elements. One row at one line
System.out.println(raggedArray[0][0] + "\t" + raggedArray[0][1]);
System.out.println(raggedArray[1][0]);
System.out.println(raggedArray[2][0] + "\t" + raggedArray[2][1] + "\t"
+ raggedArray[2][2]);
}
}
``````

``````1    2
3
4    5    6
``````

## 存取多維陣列的元素

``````public class Main {
public static void main(String[] args) {
int[][] myArray = new int[3][];
myArray[0] = new int[2];
myArray[1] = new int[1];
myArray[2] = new int[3];

// Populate the ragged array using for loops
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
myArray[i][j] = i + j;
}
}

// Print the array using for loops
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
System.out.print(myArray[i][j] + "\t");
}

// Add a new line after each row is printed
System.out.println();
}
}
}
``````

``````0    1
1
2    3    4
``````

## 初始化多維陣列

``````int[][] arr = {{10, 20, 30},
{1, 2},
{2, 3, 4, 5}};
``````

``````String[][] acronymlist = {{"A", "a"},
{"B", "b"},
{"C", "c"}};
``````

``````int[][] arr = new int[][]{{1, 2},   {3,4,5}};
``````