aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Cannot Collections.binarySearch() a collection that implements Comparable. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Cannot Collections.binarySearch() a collection that implements Comparable. " Watch "Cannot Collections.binarySearch() a collection that implements Comparable. " New topic
Author

Cannot Collections.binarySearch() a collection that implements Comparable.

O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

Im struggling to understand why these two statements are generating a compiler error



The code used is shown below


And the instances are initialised as follows



The error being generated is shown below


- Error 1 is complaining about the cities object. The Cities class implements Comparable so why is it not allowing it
- The second error is complaining about cities2. This is based on the CitiesNoComparable class. This class does not implement comparable so this error is probably justified.
- The third error is based on the same object but i am passing a Comparator in the search. Shouldnt this have been accepted?

Thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16815
    
  19

O. Ziggy wrote:
- Error 1 is complaining about the cities object. The Cities class implements Comparable so why is it not allowing it
- The second error is complaining about cities2. This is based on the CitiesNoComparable class. This class does not implement comparable so this error is probably justified.
- The third error is based on the same object but i am passing a Comparator in the search. Shouldnt this have been accepted?


It's not complaining about the Cities or CitiesNoComparable class. It's complaining about key parameter to the binarySearch method. This parameter is the same type as the generic (or super); and in both cases, you provided a string, ie. "London". It needs to be either a Cities or CitiesNoComparable instance.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

oh yes ofcourse. I was supposed to search for an object with "London" as its city. Not the actual city itself as a string.



Thanks
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Cannot Collections.binarySearch() a collection that implements Comparable.
 
Similar Threads
Use of of a Comparable object as a parameter to indexof
Comparable interface problem
Collections.binarySearch() problem
Problem with using generics
Collections.binarySearch Question