File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections Sorting

 
srinivas raju
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
thanks
srinivas
 
Mark Herschberg
Sheriff
Posts: 6037
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
--Mark
 
raimondas zemaitis
Ranch Hand
Posts: 104
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 64
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic