This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Ben Phoebi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48453
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch after 4½ years

What did you read in the API documentation? What do you not understand?
 
Knute Snortum
Bartender
Posts: 1843
13
Chrome Eclipse IDE Java Postgres Database Ubuntu VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic