1.一维数组
语法:
数组元素类型 数组名字[];
数组元素类型[] 数组名字;
赋值(第一个元素从0开始):
-
方法1:
int a[] = new int[3]; a[0] = 7; a[1] = 8; a[2] = 9;
-
方法2:
int b[] = new int[]{4,5,6};
-
方法3:
int c[] = {1,2,3};
返回数组长度:length()
,注意:
- length返回的是int类型
- 数组长度不可以定义为负数
- length的值是常量
2.二维数组
语法:
//[行][列]
数组元素类型 数组名字[][];
数组元素类型[][] 数组名字;
赋值:
-
方法1:
int tdarr1[][] = {{1,3,5},{5,9,10}};
-
方法2:
int tdarr2[][] = new int[][]{{65,55,12},{92,7,22}};
-
方法3:
int tdarr3[][] = new int[2][3]; tdarr3[0] = new int[]{6,54,71}//给第一行赋值 //给第二行赋值 tdarr3[1][0] = 63; tdarr3[1][1] = 10; tdarr3[1][2] = 7;
3.遍历数组
-
一维数组:单for循环
-
二维数组:双for循环
char arr[][] = new char[4][]; arr[0] = new char[]{'春','眠','不','觉','晓'}; arr[1] = new char[]{'处','处','闻','啼','鸟'}; arr[2] = new char[]{'夜','来','风','雨','声'}; arr[3] = new char[]{'花','落','知','多','少'}; //复杂版 for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[i].length;j++){ System.out.print(arr[i][j]); } System.out.println(); } //简约版 for(char a[] : arr){ for(char b : a){ System.out.print(b); } System.out.println(); }
4.填充和替换数组元素
语法:
//arr:数组
//value:填充的值
Arrays.fill(arr,int value)
//fromIndex:填充的第一个索引(包括)
//toIndex:填充的最后一个索引(不包括)
Arrays.fill(arr,int fromIndex,int toIndex,int value)
5.排序数组
语法:
int arr[] = new int[]{23,42,12,8};
Arrays.sort(arr);
6.复制数组
语法:
//arr:数组
//newlength:复制后的新数组的长度
Arrays.copyOf(arr,newlength)
//fromIndex:指定开始复制数组的索引位置(包括)
//toIndex:要复制范围的最后索引位置(不包括)
Arrays.copyOf(arr,fromIndex,toIndex)