SCJP 1.6版考題 010

出自 陳富國維基館
於 2013年3月30日 (六) 08:55 由 Ikk (對話 | 貢獻) 所做的修訂 (新頁面: 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. Arr...)
(差異) ←上個修訂 | 最新修訂 (差異) | 下個修訂→ (差異)
前往: 導覽搜尋
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.

解答


Ans: C

解說:

字串被排完後是:blue, green, orange, red, yellow 
Arrays.binarySearch傳回鍵值在集合中的位置,orange在陣列索引2上
Arrays.binarySearch若找不到鍵值,傳回值是:(-(insertion point) – 1,
insertion point是該鍵值在集合中的依其大小的插入點,violet應插入在yellow前,其插入點是4,-4-1得-5 
(請參考JDK的說明)