This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
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

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
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."
Sunny Jain
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: 14991

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!