Senhores, estou com uma dúvida na questão 9 do capítulo 7 (Generics and Collections) do livro da Kathy.
A questão é a seguinte:
- Given a properly prepared String array containing five elements, which range of results could a
proper invocation of Arrays.binarySearch() produce?
A. 0 through 4
B. 0 through 5
C. -1 through 4
D. -1 through 5
E. -5 through 4
F. -5 through 5
G. -6 through 4
H. -6 through 5
Answer:
G is correct. If a match is found, binarySearch()will return the index of the element that
was matched. If no match is found, binarySearch() will return a negative number that,
if inverted and then decremented, gives you the insertion point (array index) at which the
value searched on should be inserted into the array to maintain a proper sort.
A, B, C, D, E, F, and H are incorrect based on the above. (Objective 6.5)
Porém, fiz um teste:
import java.util.*;
public class Test {
public static void main(String args[]) {
String[] str = {"B", "D", "F", "H", "J"};
Arrays.sort(str);
System.out.println("Binary Search for 'A': " + Arrays.binarySearch(str, "A"));
System.out.println("Binary Search for 'B': " + Arrays.binarySearch(str, "B"));
System.out.println("Binary Search for 'C': " + Arrays.binarySearch(str, "C"));
System.out.println("Binary Search for 'D': " + Arrays.binarySearch(str, "D"));
System.out.println("Binary Search for 'E': " + Arrays.binarySearch(str, "E"));
System.out.println("Binary Search for 'F': " + Arrays.binarySearch(str, "F"));
System.out.println("Binary Search for 'G': " + Arrays.binarySearch(str, "G"));
System.out.println("Binary Search for 'H': " + Arrays.binarySearch(str, "H"));
System.out.println("Binary Search for 'I': " + Arrays.binarySearch(str, "I"));
System.out.println("Binary Search for 'J': " + Arrays.binarySearch(str, "J"));
}
}
E o resultado foi:
Binary Search for ‘A’: -1
Binary Search for ‘B’: 0
Binary Search for ‘C’: -2
Binary Search for ‘D’: 1
Binary Search for ‘E’: -3
Binary Search for ‘F’: 2
Binary Search for ‘G’: -4
Binary Search for ‘H’: 3
Binary Search for ‘I’: -5
Binary Search for ‘J’: 4
Dessa forma a resposta correta não seria a alternativa “E”?