File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections.binarySearch() problem" Watch "Collections.binarySearch() problem" New topic
Author

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:
http://java.sun.com/docs/books/tutorial/java/generics/index.html
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,
-mila-


SCJP 5
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: 14118
    
  17

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 7 API documentation
Scala Notes - My blog about Scala
Prasun Howlader
Ranch Hand

Joined: Oct 21, 2007
Posts: 89
But sort method (except comparator sort) not required this.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Collections.binarySearch() problem