创建数组,主要分三步:
- 在栈内存中声明一个数组变量,值为数组元素的首地址;
- 在堆内存中开辟空间;
- 初始化数组中的元素。
1.一维数组
声明数组变量:
//数据类型[] 数组名;
int[] a;
//数据类型 数组名[];
int b[];
为数组开辟空间:
//数据类型[] 数组名 = new 数据类型 [ 数量 ];
int[] a = new int[2];
//数据类型[] 数组名;
//数组名 = new 数据类型 [ 数量 ];
int b[];
b = new int[2];
不同数据类型的数组的默认值:
数据类型 | 默认值 |
数值类型 | 0 |
布尔类型 | false |
字符类型 | ' ' (字符串结束标志) |
引用类型 | null (空引用) |
初始化数组:
静态初始化
int[] a = new int []{1,2,3,4}; //[] 中不能有数字
int[] b = {1,2,3,4}; //数组长度由大括号中数值的个数决定
动态初始化
int[] a = new int [2];
a[0] = 1;
a[1] = 2;
foreach 遍历数组:
/*
* for(数据类型 变量名 : 数组名){ ... }
*/
for(int e : a){
System.out.println(e);
}
System.arraycopy() 复制数组:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Object src : 源数组,这个数组中的数据将会被复制到 dest 数组中
int srcPos : 复制的起始位置
Object dest : 目标数组
int destPos : 粘贴的起始位置
int length : 要 copy 的数组的长度
例:
byte[] srcBytes = new byte[]{2,4,0,0,0,0,0,10,15,50};
byte[] destBytes = new byte[5];
System.arraycopy(srcBytes, 0, destBytes, 0, 5);
for(int i = 0;i< destBytes.length;i++){
System.out.print("-> " + destBytes[i]);
}
运行结果 : -> 2-> 4-> 0-> 0-> 0
2. 二维数组
声明:
int[][] a;
int b[][];
开辟空间:
int[][] a = new int[3][3];
int[][] b = new int[3][];
b[0] = new int[1];
b[1] = new int[2];
b[2] = new int[3];
初始化:
int[][] a = {{1,2,3}, {4,5,6}, {7,8,9}};
int[][] b = new int[3][];
b[0] = new int[] {1};
b[1] = new int[] {1,2};
b[2] = new int[] {1,2,3};
int[][] c = new int[2][2];
c[0][0] = 1;
c[0][1] = 2;
c[1][0] = 3;
c[1][1] = 4;
遍历:
for(int i = 0; i<a.length; i++) {
for(int j = 0; j<a[i].length; j++) {
System.out.print(a[i][j]);
}
System.out.println();
}