File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections.binarySearch() problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections.binarySearch() problem" Watch "Collections.binarySearch() problem" New topic

Collections.binarySearch() problem

Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89

Why this program fails to compile?

"Control time instead of letting time control you."
Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Can you paste your error here..!! Well i have java 1.4 install on my system..and after changing :

I compiled and run it successfully..

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

I believe the problem is in using generics which came out in Java 5.0.

The binarySearch() method of the Collections class uses generics in an advanced way that I'm not familiar with.

Java 6 Tutorial from Sun on Generics:
Vierda Mila
Ranch Hand

Joined: Feb 25, 2008
Posts: 61
try to add <Super> after class Super implements Comparable and change parameter in compareTo method from (Object o) into (Super s)

thanks & regards,

Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89
But why not this way program not compile?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

According to the documentation of class Collections, the binarySearch method you are calling looks like this:

public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)

Especially note the type of the list. It must be a list of objects that extend Comparable, but the Comparable must also be generic. You must change your class Super so that it extends Comparable<Super>, instead of just Comparable:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89
But sort method (except comparator sort) not required this.
I agree. Here's the link:
subject: Collections.binarySearch() problem
It's not a secret anymore!