Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Comparator question

 
Kevin Crays
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On page 557 in K&B's book it says
If the collection/array you want to search was sorted in natural order, it must be searched in natural order. (This is accomplished by NOT sending a Comparator as an argument to the binarySearch() method.


Why can't you send a Comparator argument? AFAIK, there's no reason why you can't use a comparator to sort/search in naturual order (even if doing that makes little sense).
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yep ! but nobody would do it
 
Kevin Crays
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Meyers:
Yep ! but nobody would do it


There are lots of things on the test that I can't imagine anyone doing (e.g. Integer Integer = new Integer()), but the quoted paragraph, to me, implies that it cannot be accomplished using a comparator, or that it's illegal to use a comparator.

If it's never tested, then no harm, no foul. Otherwise, I think Bert and Kathy should reword it.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the wording is accurate, but could perhaps be expanded on a bit. (I don't have the book, but I'm curious whether there's more context.)

As you've noted, the idea is that the ordering scheme used by a binary search must match whatever ordering was used to sort the collection or array. If natural ordering was used, then there's no need to provide a Comparator to the search method, although you could provide a natural-ordering Comparator.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've added a note to consider softening the wording on page 557. I'm not going to count it as an errata, Maybe we'll add the word "typically" - I'm not sure yet.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic