Arrays中toString 和 binarySearch 的原代码

2023-02-25,,

只是记住方法是干什么的,但是对具体方法的理解还是不够
查找方法 当所查找的不存在的时候 返回值应该是 return -(low + 1);
 
一直知道toString 是转换成为字符串  但是具体的方法转换并不是很清楚
其中toStirng方法运用了append 和StringBuilder
 
binarySearch
int[] arr={11,22,55,66,88};
a = arr;
fronIndex = 0;
toIndex = 5;
key = 99;

key = 99;
[11,22,55,66,88];   
private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
        int low = fromIndex; // 0
        int high = toIndex - 1; // 4
        while (low <= high) {  //
            int mid = (low + high) >>> 1; // 2 , 3 ,4
            int midVal = a[mid]; //55 , 66 ,88
            if (midVal < key)
                low = mid + 1;//3 , 4, 5
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }

   
toString
int[] arr = {1,2,3,4,5};
public static String toString(int[] a) {
//a = arr
        if (a == null)  //判断数组对象是都为空
            return "null";
        int iMax = a.length - 1; //4
        if (iMax == -1)  //这个说明数组存在,但是没有元素
            return "[]";
           
  //StringBuilder的好处:线程不安全,但是效率高
        StringBuilder b = new StringBuilder();
       b.append('['); //  "["
        for (int i = 0; ; i++) {  //判断条件没有写的话,表示这个循环永远为true
            b.append(a[i]); //"[1"  , //"[1, 2"
            if (i == iMax){ //i = 0, imax = 4
                return b.append(']').toString(); "[1, 2, 3, 4, 5]".toString();
            }   
            b.append(", "); //"[1, "   , "[1, 2, "
        }
    }
可能这次写的不太多但是从各种方法的原代码和方法的重写  其实都是可以通过简单的代码一步步实现的
掌握熟练基础才是真正的关键 
 
 
个人观点 

Arrays中toString 和 binarySearch 的原代码的相关教程结束。

《Arrays中toString 和 binarySearch 的原代码.doc》

下载本文的Word格式文档,以方便收藏与打印。