18.Arrays类
Arrays类
1.打印数组元素
int[] a = {1,2,3,4,9094,203293,32,311,3};
//利用Arrays工具类,打印数组元素Arrays.toString()
System.out.println(Arrays.toString(a));
输出:
[1, 2, 3, 4, 9094, 203293, 32, 311, 3]
可以不用自己写方法遍历数组元素再输出。
int[] a = {1,2,3,4,9094,203293,32,311,3};
printArray(a);
//编写方法给主方法调用
public static void printArray(int[] a){
for (int i = 0; i < a.length; i++) {
if(i == 0){
System.out.print("[");
}
if(i == a.length - 1){
System.out.print(a[i] + "]");
}else{
System.out.print(a[i] + "," + " ");
}
}
}
输出:
[1, 2, 3, 4, 9094, 203293, 32, 311, 3]
2.数组元素排序
int[] a = {1,2,3,4,9094,203293,32,311,3};
Arrays.sort(a);//默认升序
System.out.println(Arrays.toString(a));
输出:
[1, 2, 3, 3, 4, 32, 311, 9094, 203293]
3.数组填充
int[] a = {1,2,3,4,9094,203293,32,311,3};
Arrays.fill(a ,0);//全填充
System.out.println(Arrays.toString(a));
输出:
[0, 0, 0, 0, 0, 0, 0, 0, 0]
Arrays.fill(a,2,4 ,0);//(a ,fromIndex:2 ,toIndex:4 ,val:0),部分填充
System.out.println(Arrays.toString(a));
输出:
[1, 2, 0, 0, 4, 32, 311, 9094, 203293]
由下标为2的元素到下标为4的元素填充为0。区间为左闭右开。