1.数组的声明与使用
int[] a = new int[10];
float[] f= new float[33];
double[] d = new double[213];
char[] c = new char[21];
//数组的初始化
int[] a = {1,2,3};
int[] b = new int[3];
char[] d = {'a','b','c'};
//数组访问
int[] a={0,1,2};
System.out.println("%d %d %d\n",a[0],a[1],a[2]);
a[0]=5;
System.out.println("%d %d %d\n",a[0],a[1],a[2]);
2.使用数组完成斐波那契数列
int n = sc.nextInt();
int[] f = new int[n+1];
f[0] = 0;
f[1] = 1;
for(int i=2;i<=n;i++){
f[i]=f[i-1]+f[i-2];
}
System.out.println(f[n]);
3.多维数组
int[][] a = new int[3][4];
int[][][] b = new int[3][4][5];
int[][] a = {
{0,1,2,3},
{4,5,6,7},
{8,9,10,11},
};
for(int i=0;i<3;i++){
for(int j=0;j<4;j++){
System.out.printf("%d ",a[i][j]);
}
System.out.println();
}
4.常见的API
(1)属性length:返回数组的长度
int[] arr = new int[5];
System.out.println(arr.length);
(2)Array.sort()函数:数组顺序排序
int n = sc.nextInt();
int[] q = new int[n];
for(int i=0;i<n;i++) q[i] = sc.nextInt();
Arrays.sort(q);
for(int i=0;i<q.length;i++){
System.out.println(q[i]);
}
//如果想倒叙排序:必须把int类型改为Integer对象
int n = sc.nextInt();
Integer[] q = new Integer[n];
for(Integer i=0;i<n;i++) q[i] = sc.nextInt();
Arrays.sort(q,(x,y)->{
return y-x;
});
for(int i=0;i<q.length;i++){
System.out.println(q[i]);
}
//二维数组排序:不需要转化为Integer,因为二维数组本身是对象
int[][] a= {
{4,5,6,7},
{0,1,2,3},
{8,9,10,11},
};
Arrays.sort(a,(x,y)->{
return x[0]-y[0];
});
System.out.println(Arrays.deepToString(a));
(3)Arrays.toString()函数:将数组转化为字符串
System.out.println(Arrays.toString(q));
(4)Arrays.deepToString()函数:将多维数组转化为字符串
System.out.println(Arrays.deepToString(q));
(5)Arrays.fill(int[]a,int val)函数:填充数组,只能初始化一维数组
int[] a = new int[10];
Arrays.fill(a,-1);
System.out.println(Arrays.toString(a));