File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Arrays.sort and Arrays.binarySearch methods that take Comparator Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arrays.sort and Arrays.binarySearch methods that take Comparator Objects" Watch "Arrays.sort and Arrays.binarySearch methods that take Comparator Objects" New topic
Author

Arrays.sort and Arrays.binarySearch methods that take Comparator Objects

Ben Phoebi
Greenhorn

Joined: Jan 08, 2009
Posts: 4
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?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
Welcome to the Ranch after 4½ years

What did you read in the API documentation? What do you not understand?
Knute Snortum
Greenhorn

Joined: Apr 20, 2013
Posts: 3
Here a guess at what's confusing you.

You have a sorted int array:



You execute this code:



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?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arrays.sort and Arrays.binarySearch methods that take Comparator Objects
 
Similar Threads
Array.binarySearch()
Please explain the code.
binarySearch() method of Arrays
confused about collections
Searching an array?