# Java 多维数组

2018-01-23 18:42 更新

## Java数据类型教程 - Java多维数组

`int[][] table;`

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

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

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

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

table [0]，table [1]和table [2]是int数组，我们可以将它们赋值为

```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]);
}
}
```

## 访问多维数组的元素

```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();
}
}
}
```

## 初始化多维数组

```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}};
```

App下载