Java二维数组的声明和初始化
文章目录
1. Shortcut Syntax
Java二维数组最常用的声明初始化方法
int[][] arr =
{
{1, 2, 3},
{4, 3, 6},
{7, 8, 9}
};
or
int[][] arr =
{
{ 1 },
{ 1, 2 },
{ 1, 2, 3 }
};
2. New Operator
用new操作符来声明初始化
如果我们没有自己提供值,数组将自动为每个元素赋默认值
int[][] arr; // declare array
arr = new int[3][4]; // allocate memory
or
int[][] arr = new int[3][4];
3. Skipping second dimension
先指定第一维度,再指定第二维度
int[][] arr = new int[3][];
arr[0] = new int[4];
arr[1] = new int[4];
arr[2] = new int[4];
or
int[][] arr = new int[3][];
arr[0] = new int[1];
arr[1] = new int[2];
arr[2] = new int[3];
This will create a two dimensional array as shown below:
[0]
[0, 0]
[0, 0, 0]
or
int[][] arr = new int[3][];
arr[0] = new int[] { 1 };
arr[1] = new int[] { 1, 2 };
arr[2] = new int[] { 1, 2, 3 };
Above codes will result in:
[1]
[1, 2]
[1, 2, 3]
4. Reflection(反射)
通过反射来创建指定类型的二维数组
例如,创建3 x 4
的二维数组
int[][] arr = (int[][]) Array.newInstance(int.class, 3, 4);
5. Initialize character array
使用String.toCharArray()
方法创建character二维数组
char[][] ch =
{
"ABCD".toCharArray(),
"EF".toCharArray(),
"GHI".toCharArray()
};
6. Initialize Object array
使用 new Type()
将二维对象数组初始化
as shown below
Foo[][] array =
{
{ new Foo(), new Foo(), ... new Foo() },
{ new Foo(), new Foo(), ... new Foo() },
... ... ...
... ... ...
{ new Foo(), new Foo(), ... new Foo() }
}
or, we can initialize it with nulls using below syntax
Foo[][] array = new Foo[3][4];