I am preparing for d OCPJP 6 exam and going through a Practice Exam textbook. I came across a question about the outcome of the execution of a class that implements the Comparator interface. The class has a main method in which an array of the class type contains objects of the class. The array is sorted with the Arrays.sort method and Arrays.binarySearch method is used to searcn for an object that is in the array. The binarySearch method is used again to search for an object that does not exist in the array. Even though I have executed the program on my JVM, and seen that the answer given by the book is correct, I still dont understand why the program should give some results. So I said to myself: "May be there is something extra that I dont understand in the Arrays.binarySearch method that takes Comparator arguments or the working of the Comparator compare method or the Arrays.sort method", because I have been in and out of the Comparator and Arrays.sort and binarySearch methods in JDK 6 and 7 API Doc. Can I get a hand?
After that, b == -4. Why? Any positive number is the index of the number found in the array. If the number is not found, it will always be negative. It uses this formula: -(insertion_point) - 1. In this case, the insertion point for be at index 3 sp it returns -(3) - 1 = -4. Make sense?
subject: Arrays.sort and Arrays.binarySearch methods that take Comparator Objects