• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to use Collections.binarySearch()

 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I use Collections.binarySearch() with list of objects (not String, not Wrapper classes), Do I need to override equals() method??
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, String is already implementing the Comparable interface, so you don't need anything. In fact, it has nothing to do with equals(). but with Comparable or Comparator. You either implement Comparable, or you provide your own Comparator and pass it as the third parameter of binarySearch.
 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Satou

But what key used to search list of third-party objects?

such as (from K&B book):

ArrayList<DVDInfo> DVDList = new ArrayList<DVDInfo>();

int index = Collections.binarySearch(this.DVDList, this.DVDList.get(0));
System.out.println("found at index: " + index); // work

But when I pass a new instance of DVDInfo

DVDInfo dvd = new DVDInfo("smallvile", "classic", new Date());

int index = Collections.binarySearch(this.DVDList, dvd);
System.out.println("found at index: " + index); // not found, return -3, there are only 2 elements in the list???



DVDInfoList.txt
smallvile, classic, 10/11/06
borat, drama, 02/05/06

thanks
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're showing the content of a text file, but not the content of the List. Try to dump the list, to make sure that all dvds are in there.
 
Anthony Karta
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is the outp Output
[smallvile - classic, borat - drama]
After sort: [borat - drama, smallvile - classic]

1st search found at index: 0

2nd search found at index: -3 // why -3 ?? not -1


and I still confuse, when we invoke this statement:

Collections.binarySearch(this.DVDList, this.DVDList.get(0))

is binarySearch method use the same fields/attributes used in compare() method implementation??
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic