数组的定义
// 创建数组的方式1
double[] arr1 = {5, 4, 8, 6}
// 方式2
double[] arr2 = new double[5] // 创建一个长度为5的数组,暂时还没元素
arr[0] = 1
// ...
方式3
double arr3[] // 声明数组,此时arr3还是null
arr3 = new double[5] // 分配内存空间,可以存放数据
数组的注意细节
- 数据类型要相同
- 数组创建后没有赋值,会有默认值,int,short,double,float,byte,long都是0,Boolean是false,String是null,char是\u0000。
数组的扩容
- 定义初始数组
int[] arr = {1,2,3} - 定义新数组
int[] arr2 = new int[arr.length + 1] - 遍历数组arr,把里面所有值赋值给arr2
- 为arr2新增一个元素arr[3]
- 让arr指向arr2,
arr = arr2
二维数组
int [][] arr2 = {{1,2}, {3,4}, {5,6}}
int[][] arr = new int[5][5]
二维数组应用示范:杨辉三角
public class A {
public static void main(String[] args) {
// 打印10 行杨辉三角
int[][] yanghui = new int[10][];
for (int i = 0; i < yanghui.length; i++) {
yanghui[i] = new int[i + 1];
for (int j = 0; j < yanghui[i].length; j++) {
if (j == 0 || j == yanghui[i].length - 1) {
yanghui[i][j] = 1;
} else {
yanghui[i][j] = yanghui[i - 1][j] + yanghui[i - 1][j - 1];
}
}
}
for (int i = 0; i < yanghui.length; i++) {
for (int j = 0; j < yanghui[i].length; j++) {
System.out.print(yanghui[i][j] + " ");
}
System.out.println();
}
}
}