一维数组
public static void main(String[] args) {
// 数组可以存放一批相同类型的数据
int [] arr = {1,2,3,4};
int[] arr2 = new int[] {5,6,7,8};
//数组长度不可变
System.out.println(arr2.length);
//数组长度
//数组下标从零开始
int[] arr4 = new int[5] ;//数组默认初始化 默认都是0(int类型等)或 空(String类型等)
System.out.println(arr4); //[I@7852e922 - 地址
//arr4[5] = 10;//ArrayIndexOutOfBoundsException 数组下标越界
arr4 = new int[6];//new一个新的空间
System.arraycopy(arr, 0, arr4, 0, 4);
/*第一个参数 被复制的数组名称
第二个参数 从哪个元素开始复制 数字为下标
第三个参数 复制到的目标数组名称
第四个参数 从哪个元素开始粘贴
第五个参数 取的数组长度
*/
System.out.println(Arrays.toString(arr4));//用该方法才能输出数组
}
总结:
1.数组定义时必须定义数组长度,且数组长度不可变,会默认初始化。
但可用类似语句arr4 = new int[6] new一个新的空间
2.数组下标从0开始
3.数组内容输出语句:System.out.println(Arrays.toString(arr));
二维数组
/*
* 定义一个int[]类型的数组a
* a数组中的第二个元素有三个元素,其中第三个元素是3
* a数组中的第三个元素有五个元素, 其中第四个元素是5
* 定义一个int类型数组b,b中有4个元素
* b数组中的第三个元素有两个元素,分别是2和1
* 定义一个int[]类型数组c,c中有三个元素
* c数组中每个元素有4个元素
* c数组中的第一个元素中4个元素都是1
* 第二个元素中4个元素都是2..以此类推
*/
int[][] a = new int[3][]; //理论上的二维数组
a[1] = new int[3];
a[1][2] = 3;
a[2] = new int[5];
a[2][3] = 5;
int[][] b =new int[4][];
b[2] = new int[2];
b[2][0] = 2;
b[2][1] = 1;
int[][] c = new int[3][4];
int i,j;
for(i = 0; i < c.length ; i++) {
for(j = 0; j < c[i].length ; j++) {
c[i][j] = i+1;
}
}
for(int t = 0; t < c.length ;t++) {
System.out.println(Arrays.toString(c[t]));
}
int [][] d = new int [][]{{1,2,3},{1,2,3}};//定值初始化数组
for(int t = 0; t < d.length ;t++) {
System.out.println(Arrays.toString(d[t]));
}
注意:
- int[][] a = new int[3][]; 定义时,必须定义第一个维度的元素个数,即房间个数,但不一定定义房间中人的个数。
- int[][] a = new int[3][]; int[] a[]= new int[3][]; int a[][]= new int[3][]; 都是合法的
常用数组的复制
(一)System.arraycopy(arg0, arg1, arg2, arg3, arg4);
/*第一个参数:原数组
* 第二个参数 从原数组第几个元素开始复制
* 第三个参数 目标数组
* 第四个参数 从目标数组的第几个元素开始赋值
* 第五个参数 复制元素个数 *
*/
(二)Arrays.copyOf(a,a.length+1); 会生成一个新的数组。
(三)数组的扩容,缩容实际应用
缩容:
Father hitted = flyings[temp]; //temp为被击毁飞机标号
flyings[temp] = flyings[flyings.length - 1];
flyings[flyings.length - 1] = hitted; //将被击毁的目标转移到数组最后
flyings = Arrays.copyOf(flyings,flyings.length-1); //数组缩容
扩容:
flyings = Arrays.copyOf(flyings, flyings.length + 1);//扩容
flyings[flyings.length - 1] = obj;//将新目标添加到最后一个元素上