This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Java in General and the fly likes Comparator question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparator question" Watch "Comparator question" New topic

Comparator question

Graham VMead
Ranch Hand

Joined: Sep 22, 2003
Posts: 154

I want to sort a list of session beans by their string session keys so I implemented the following.

If I want to search this sorted list using Collections.binarySearch with the search key as a String and using the same comparator how do I know whether objA or objB will be the search String and which will be the bean.

Will I need to do the following

Hope this makes sense, I know I should be checking the bean class and throwing ClassCastExceptions etc but I've left it out for clarity.
[ July 07, 2006: Message edited by: Graham VMead ]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24193

There's no other obvious way to do it; what you've done makes perfect sense.

Regarding type-checking: it's generally considered OK to just cast obliviously in Comparators, without explicit checking. When you call sort() using such a Comparator, then it would make sense to catch ClassCastException.

[Jess in Action][AskingGoodQuestions]
Graham VMead
Ranch Hand

Joined: Sep 22, 2003
Posts: 154
Thanks for the reply Ernest: Thats what I'll do then
I agree. Here's the link:
subject: Comparator question
It's not a secret anymore!