import java.util.Arrays //导入包,均为静态方法
1.数组转字符串
//一维数组
int[] array = new int[]{1, 2, 3};
System.out.println(Arrays.toString(array)); //[1, 2, 3]
//二维数组
int[][] deepArray = new int[][]{{1, 3},{2, 4}};
System.out.println(Arrays.toString(deepArray)); //[[I@1540e19d, [I@677327b6]
System.out.println(Arrays.deepToString(deepArray)); //[[1, 3], [2, 4]]
2.填充数组
array = new int[5];
Arrays.fill(array, 2);
System.out.println(Arrays.toString(array)); //[2, 2, 2, 2, 2]
//部分填充
array = new int[5];
Arrays.fill(array, 1, 4, 2);
System.out.println(Arrays.toString(array));//[0, 2, 2, 2, 0], 下标1-4填充2
3.数组元素排序
array = new int[]{3, 10, 4, 0, 2};
Arrays.sort(array);
System.out.println(Arrays.toString(array)); //[0, 2, 3, 4, 10]
array = new int[]{3, 10, 4, 0, 2};
Arrays.parallelSort(array); //和sort相比是这个是并行的
System.out.println(Arrays.toString(array)); //[0, 2, 3, 4, 10]
array = new int[]{3, 10, 4, 0, 2};
Arrays.sort(array, 0, 4); //部分排序
System.out.println(Arrays.toString(array)); //[0, 3, 4, 10, 2]
4.数组的比较
array = new int[]{1, 2, 3};
int[] array2 = new int[]{1, 2, 3};
System.out.println(Arrays.equals(array, array2)); //true
int[][] deepArray1 = new int[][]{{1, 3},{2, 4}};
int[][] deepArray2 = new int[][]{{1, 3},{2, 4}};
System.out.println(Arrays.equals(deepArray1, deepArray2)); //false
System.out.println(Arrays.deepEquals(deepArray1, deepArray2)); //true
5.数组复制
array = new int[]{3, 10, 4, 0, 2};
int[] arrayCopy = Arrays.copyOf(array, 3);
System.out.println(Arrays.toString(arrayCopy)); //[3, 10, 4]
arrayCopy = Arrays.copyOf(array, 7);
System.out.println(Arrays.toString(arrayCopy)); //[3, 10, 4, 0, 2, 0, 0], 多出的长度补0
arrayCopy = Arrays.copyOfRange(array, 1, 4);
System.out.println(Arrays.toString(arrayCopy)); //[10, 4, 0]
6.二分查找返回下标
array = new int[]{0, 3, 4, 10, 20};
System.out.println(Arrays.binarySearch(array, 10)); //3, array必须是排序的,否则得到的是错误的结果
System.out.println(Arrays.binarySearch(array, 6)); //-4, 找不到的值,从-1开始,6如果存在下标是3, 所以返回-4
System.out.println(Arrays.binarySearch(array, 2, 5, 10)); //3, 返回的还是全局的下标值。
7.数组转List
//数组转链表必须使用封装类,不然只记录数组的基本类型
int array = new int[]{3, 10, 4, 0, 2};
System.out.println(Arrays.asList(array).contains(3)); //false
Integer arr[] = new Integer[]{3, 10, 4, 0, 2};
System.out.println(Arrays.asList(arr).contains(3)); //true
//分部解析
int array = new int[]{3, 10, 4, 0, 2};
List<int[]> ints = Arrays.asList(array);
Integer arr[] = new Integer[]{3, 10, 4, 0, 2};
List integers = Arrays.asList(arr);