File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Collections Sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Collections Sorting" Watch "Collections Sorting" New topic

Collections Sorting

srinivas raju

Joined: Nov 27, 2001
Posts: 5
Can anyone Help me in Sorting a Collection
which i need to sort when clicked on a link and reverse it again when clicked on the same link.
the sorting is breaking if a have an empty string
in the Collections?
Mark Herschberg

Joined: Dec 04, 2000
Posts: 6037
How exactly is it breaking? This is just speculation but I'm guessing....
If you're using default sorting methods, it sorts strings by their hashcode. The empty string (i.e. new String("")) has a hashcode of 0 and should work fine. The null string (i.e. null), on the other hand will cause problems. In that case, you'll need to overwrite the sorting algorithm to check for null, and explicitly return 0, or some other appropriate value in that case.
raimondas zemaitis
Ranch Hand

Joined: Feb 23, 2001
Posts: 104
from my experience the most reliable way is to use
Collections.sort(type_of_your_collection, new Comparator() {
public boolean compare(Object o1, Object o2) {
//now compare what you need here
srinivas raju

Joined: Nov 27, 2001
Posts: 5
thanks for replying .i used The collection functions sort() and reverse() to get the desired result. it works fine if there is data in vector.but if i have an empty string it is not working. i any one faced similar problem please help
Roshan Lal
Ranch Hand

Joined: Nov 13, 2001
Posts: 64
I just tested a program with empty strings, using default alphabatical sorting, in the list. It works just fine. I used Sun JDK 1.3.1
[ February 04, 2003: Message edited by: Roshan Lal ]
I agree. Here's the link:
subject: Collections Sorting
It's not a secret anymore!