import java.util.*;public class TestArray{
public static void main(String[] args){
int[] num = {2,1,3,4,5};
Arrays.sort(num);
Arrays.fill(num,1,2,6);
System.out.println(Arrays.binarySearch(num,6));
}
}
应该显示是几呢?我想应该是1,可输出是-6.为什么呢?

解决方案 »

  1.   


    int[] num = {2,1,3,4,5};
    Arrays.sort(num);
    System.out.println(Arrays.toString(num));
    Arrays.fill(num,1,2,6);
    System.out.println(Arrays.toString(num));
    //Searches the specified array of ints for the specified value using the binary search algorithm. 
    //The array must be sorted (as by the sort(int[]) method) prior to making this call. 
    //If it is not sorted, the results are undefined. 
    //If the array contains multiple elements with the specified value, 
    //there is no guarantee which one will be found.
    System.out.println(Arrays.binarySearch(num,6));
      

  2.   


    Arrays.fill(num,1,2,6);是指吧num数组的第二个和第三个元素设置为6,完成后数组长度依然是5
    好好看看api啊
      

  3.   

    二分查找必先排序再查找
    api原话
    使用二分搜索法来搜索指定的 int 型数组,以获得指定的值。必须在进行此调用之前对数组进行排序(通过 sort(int[]) 方法)。如果没有对数组进行排序,则结果是不确定的。如果数组包含多个带有指定值的元素,则无法保证找到的是哪一个。