Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections.binarySearch() problem

 
Prasun Howlader
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why this program fails to compile?
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try to add <Super> after class Super implements Comparable and change parameter in compareTo method from (Object o) into (Super s)

thanks & regards,
-mila-
 
Prasun Howlader
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But why not this way program not compile?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15484
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Prasun Howlader
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But sort method (except comparator sort) not required this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic