工具类的使用
- 要多使用这个类,同时,很多算法包含其中,常见操作排序、查找、填充、打印等.
1、打印数组 ------Arrays.toString()
1 // 整型初始化 2 int[] integerInitialization = {1, 2, 3, 4, 5, 6, 7, 8, 9}; 3 4 // 打印数组 5 System.out.println("输出数组:" + Arrays.toString(integerInitialization));
2、排序(从小到大) -------Arrays.sort()
1 // 整型初始化 2 int[] integerInitialization = {100, 2, 30, 24, 35, 6, 57, 18, 9}; 3 4 // 排序 5 Arrays.sort(integerInitialization); 6 7 // 从小到大数组 8 System.out.println("输出数组:" + Arrays.toString(integerInitialization));
3、填充 -----------Arrays.fill()
1 // 整型初始化 2 int[] integerInitialization = {101, 2, 30, 24, 35, 6, 57, 18, 9}; 3 4 // 将3-6位置的元素替换为100 5 Arrays.fill(integerInitialization, 3, 6, 100); 6 7 // 打印数组 8 System.out.println("输出数组:" + Arrays.toString(integerInitialization));
4、查找(二分查找法) ---------Arrays.binarySearch()
1 // 整型初始化 2 int[] integerInitialization = {101, 2, 30, 24, 35, 6, 57, 18, 9}; 3 4 // 排序 5 Arrays.sort(integerInitialization); 6 7 // 排序后数组 8 System.out.println(Arrays.toString(integerInitialization)); 9 10 // 二分查找,关键字30 11 int binarySearchResult = Arrays.binarySearch(integerInitialization, 30); 12 13 // 打印数组 14 System.out.println("返回排序后的索引值数组:" + binarySearchResult);
注意
- 此处的Arrays.toString()方法是Arrays类的静态方法,不是前面讲的Object的toString()方法.
- 数据元素引用类型的排序,需要实现Comparable接口