第10題
Given:
1. import java.util.*;
2. public class Quest{
3. public static void main(String[] args){
4. String[] colors =
5. {"blue","red","green","yellow","orange"};
6. Arrays.sort(colors);
7. int s2 = Arrays.binarySearch(colors, "orange");
8. int s3 = Arrays.binarySearch(colors, "violet");
9. System.out.print(s2 + "" + s3);
10. }
11. }
What is the result?
A. 2-1
B. 2-4
C. 2-5
D. 3-1
E. 3-4
F. 3-5
G. Compilation fails.
H. An exception is thrown at runtime.
答案:C请大牛们帮我分析下这个过程,谢谢了。。

解决方案 »

  1.   

    首先:sort(colors);
    原数字变为:{"blue","green","orange","red","yellow"},这个没问题!
    其次:int s2 = Arrays.binarySearch(colors, "orange");
    这是s2 = 2,也没问题,就是orange的索引号。
    再次:int s3 = Arrays.binarySearch(colors, "violet");
            由于不存在这个值,所以会返回-4-1=-5.因为文档上说:
    如果数组中不存在这个值那么会返回(-(插入点) -1),所谓插入点就是数组中正好比所查的元素大的哪一个点的索引。
    比如“violet”不在数组中,所以正插入好比“violet”大的是orange,所以插入点就是orange的索引4.
    所以会返回:-4-1=-5.
    具体你看arrays的文档,它就是这么说的。
      

  2.   

    学习,说下理解排序后的数组如下
    [blue, green, orange, red, yellow]
    如果存在的话,返回其索引 orange的索引是2
    如果不存在,返回它刚好大于的那个元素的索引+1,用负号表示不存在
    violet大于数组中每一个元素,所以它的返回值是最大的索引号+1
    Arrays.binarySearch(colors, "happy");
    返回值是-3
      

  3.   

    比violet大一点的应该是yellow,yellow的索引是4,-4-1=-5吧