Arrays类的几个方法及源码分析

xiaoxiao2021-02-28  82

Arrays类

方法

public static String toString(int[] a) 返回指定数组内容的字符串表示形式。 字符串表示形式由数组的元素列表组成,括在方括号("[]")中。 相邻元素用字符 ", "(逗号加空格)分隔。 这些元素通过 String.valueOf(int) 转换为字符串。 如果 a 为 null,则返回 "null"。  参数: a - 返回其字符串表示形式的数组  返回: a 的字符串表示形式

源码分析

public static String toString(int[] a) { if (a == null) //如果传入的数组是null return "null";//返回null int iMax = a.length - 1;//iMax最大索引 if (iMax == -1) //如果数组中没有元素 return "[]";//返回[] StringBuilder b = new StringBuilder(); //线程不安全,效率高 b.append('['); //将[添加到字符串缓冲区中 for (int i = 0; ; i++) { //遍历数组,判断语句没有写默认是true b.append(a[i]); //把第一个元素添加进字符串缓冲区 if (i == iMax) //如果索引等于了最大索引值 return b.append(']').toString();//将]添加到字符串缓冲区,在转换成字符串并返回 b.append(", ");//如果不等于最大索引就将, 添加到缓冲区 } } public static void sort(int[] a) 对指定的 int 型数组按数字升序进行排序。 该排序算法是一个经过调优的快速排序法, 参数: a - 要排序的数组 public static int binarySearch(int[] a,int key) 使用二分搜索法来搜索指定的 int 型数组,以获得指定的值。 必须在进行此调用之前对数组进行排序(通过 sort(int[]) 方法)。 如果没有对数组进行排序,则结果是不确定的。 如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。  参数: a - 要搜索的数组 key - 要搜索的值  返回: 如果它包含在数组中,则返回搜索键的索引; 否则返回 (-(插入点) - 1)。插入点 被定义为将键插入数组的那一点: 即第一个大于此键的元素索引,如果数组中的所有元素都小于指定的键,则为 a.length。 注意,这保证了当且仅当此键被找到时,返回的值将 >= 0。

源码分析

private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; //最小索引0 int high = toIndex - 1; //最大索引数组长度-1 while (low <= high) { //最小索引小于等于最大索引可以循环判断 int mid = (low + high) >>> 1;//求出中间索引值,(最小+最大)/2 int midVal = a[mid]; //通过中间索引获取中间值 if (midVal < key) //中间索引对应的值小于查找的值 low = mid + 1; //最小索引变化 else if (midVal > key) //中间索引对应的值大于查找的值 high = mid - 1; //最大索引变化 else return mid; // key found //找到了 } return -(low + 1); // key not found.//-插入点 - 1 import java.util.Arrays; public class arrdemo { public static void main(String[] args) { // TODO Auto-generated method stub int[] arr = {1,11,54,6,8,45,4}; System.out.println(arr.toString()); System.out.println(Arrays.toString(arr)); //[1, 11, 54, 6, 8, 45, 4] Arrays.sort(arr); System.out.println(Arrays.toString(arr)); //[1, 4, 6, 8, 11, 45, 54] int[] arr1 = {1,11,54,6,8,45,4,55,17,59,13}; Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); //[1, 4, 6, 8, 11, 13, 17, 45, 54, 55, 59] System.out.println( Arrays.binarySearch(arr1, 55));//9 System.out.println( Arrays.binarySearch(arr1, 88));//-12 (-11-1) -(插入点) - 1 System.out.println( Arrays.binarySearch(arr1, 0));//-1 } }
转载请注明原文地址: https://www.6miu.com/read-62434.html

最新回复(0)