Java -数组
1.一维数组
1.1数组定义
public class Main {public static void main(String[] args) throws Exception {int[] a = new int[10];float[] f = new float[10];double[] d = new double[10];char[] c = new char[10];}
}
1.2 初始化
public class Main {public static void main(String[] args) throws Exception {int[] a = {0, 1, 2};int[] b = new int[3];char[] d = {'a', 'b', 'c'};}
}
1.3 访问数组
public class Main {public static void main(String[] args) throws Exception {Scanner sc=new Scanner(System.in);int n=sc.nextInt();int[] a=new int[100];for(int i=0;i<n;i++){a[i]=sc.nextInt();}for(int i=0;i<n;i++){System.out.printf("%d ",a[i]);}}
}
2.多维数组
public class Main {public static void main(String[] args) throws Exception {int[][] a = new int[5][5]; // 大小为5的数组,每个元素是含有5个整数的数组。int[][][] b = new int[1][2][3]; // 大小为1的数组,它的每个元素是含有2个数组的数组// 这些数组的元素是含有3个整数的数组}
}
3.二维数组的遍历
public class Main {public static void main(String[] args) throws Exception {int[][] a = {{4,6,2,8}, {0,7,1,3}, {234,465,12}};for (int[] row: a) {for (int x : row) {System.out.printf("%d ", x);}System.out.println();}}
}
4.常用的API
length:返回数组长度,注意不加小括号
Arrays.sort():数组排序
Arrays.fill(int[] a, int val):填充数组
Arrays.toString():将数组转化为字符串
Arrays.deepToString():将多维数组转化为字符串