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

Sorting collection of objects

Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
Hi
I have a collection of objects, which I want to sort based on a particular string field in the object. I am trying to find the best way to hold these objects, so that sorting can be done in an efficient way.
1) Should I declare an array to hold the objects and write my own algorithm to sort the objects in the array by checking the string field of each object in the array with the rest of the objects?
2)Should I use the Arrays class in java.util and use the sort() method to sort the objects in which case I need to implement the Comparator interface.
3)Or any other method, if any one could suggest (which I am not familiar being a new bee to Java)
Appreciate all your comments and suggestions.
Thanks
Kelly
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
If all of the objects are instances of the same class, then probably the easiest way to go is for that class to implement the Comparable interface. Then you can use Arrays.sort(myObjects) or gather them into a SortedSet and let it sort as objects are added.
Michael Morris


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Seconded. You would never write your own sorting routine. Most of the time, the ones in Arrays and Collections are better than anything you could come up with.
If you have an array, there is just one way to sort that, using Arrays.sort(). (There's still the choice between Comparable and Comparator; more about that in a mo).
If you use collections, there are two ways to sort: you can sort a List using Collections.sort(), or you can use a sorted collection such as SortedSet. How to choose between them? Pick SortedSet if (1) you never have the same element twice, and (2) you regularly add or remove elements from the collection and you need to keep it sorted all the time. Otherwise, use a List and Collections.sort() that list whenever you need to.
When sorting an array or collection of objects, you need some idea of when an object is "greater" than another object. Both Comparator and Comparable serve this function. How to choose? Basically, when you only ever need to sort in one way, or when one particular way of sorting is a "natural sorting order", make your class implement Comparable. Otherwise, when there are multiple possible ways of sorting and they are all equally valid, create a Comparator for each sorting order.
By the way, if your class has a natural sorting order (i.e. implements Comparable) then you can easily reverse the sorting using Collections.reverseOrder(). It's a pity there's no overloaded version that takes a Comparator and reverses it.
- Peter
[ March 28, 2003: Message edited by: Peter den Haan ]
Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
Hi Michael
Yes, all the objects are instances of the same class. Thanks for your suggestion. I will implement Comparable interface and use Arrays to sort.
Thanks
Kelly
Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
Hi Peter
Thanks for your detail explanation. I appreciate your comments. I am glad I posted my question in this message board.
When I opened my posting this morning, I was not able to see your response. Hence the delay in acknowledging!
Thanks
Kelly
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
See TreeSet in JDK 1.4, too. It may be more efficient to create an unsorted Collection then create new TreeSet( unsortedSet ).
I don't think you have to have all the same class to use Comparable - just compatible classes that won't throw exceptions when asked to compare to each other.
Collections Crib Sheet


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451

I don't think you have to have all the same class to use Comparable - just compatible classes that won't throw exceptions when asked to compare to each other.

That's right, but since when does it make sense to compare Apples and Oranges (please forgive the cliche )? And while it is not part of the general contract of Comparable that the compared objects have a common ancestry, one should be wary of the avenue of abuse that sort of coding opens up. If I say it is OK to compare a Foo with a Bar and they are only related thru Object, then in my humble opinion, I'm following the same old bad practices I used to follow when coding in C++ when I used operator overloading to accomplish a task totally unrelated to the particular operator.
Michael Morris
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
CA Guy,

Please change your name to be compliant with JavaRanch's naming policy. It should not be obviously fictitious.
Your displayed name should be 2 separate names with more than 1 letter each. We really would prefer that you use your REAL name.
You can change your name: here.
Thanks,
Cindy


"JavaRanch, where the deer and the Certified play" - David O'Meara
Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
I am using Arrays.sort() to sort the array of objects I have. I am getting a NullPointerException when I call Arrays.sort (array of objects, Comparator class).
Yes, I did implement Comparator classes for each of the sorting order in which my array of objects has to be sorted. I am not sure what I am doing wrong, I am getting NullPointerException. When I notice my run time error message, the error message is specifically pointing to my Arrays.sort() call and the Comparator class’s compare() method’s second object.
In “public int compare(Object obj1, Object obj2)” method definition, the run time error message points to the line where I refer obj2 in my comparison. I don’t know whether this is helpful or not, I just thought of mentioning.
I greatly appreciate all your comments and suggestions.
Thanks!
Kalyani
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Do you have any null elements in your array?
- Peter
Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
Peter,
I don't think I have null elements in the array. I printed the array of objects, just before sorting and checked the data. May be I will check the array for null elements once again and see.
Thanks
Kalyani
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
The NullPointerException will be due either to null elements in your array, or perhaps due to instance variables that you use in compare() being null. The stack trace should provide more information about this.
If you can't figure it out, post your compare() and the stack trace.
- Peter
Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
Hi Peter
Thanks for your suggestion. You are right, I think I do have null elements in the array.
I am converting a C code into Java. I just noticed the C program, the array is declared with a size of 2400, so in the Java program also I declared the array size to be 2400.
But I do know, the number of objects that filled into the array is around 320. Probably thats the reason I am getting NullPointerException in my compare().
I don't have my Java code with me as this is an evening project for me. I will check that in the evening. I am pretty sure that is my problem.
Thanks Peter for pointing to the right direction. If this is not fixing the problem, I will post the stack trace and compare() code.
Thanks a lot.
Kelly
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
If you aren't sure of the number of elements in the array, you should use Vector or some other Collection object to store the data. These all have dynamic memory management built into them, so that the memory used expands as you add more elements. I'm pretty sure they all provide sort() routines as well.


Java API Documentation
The Java Tutorial
Kelly KMoni
Greenhorn

Joined: Apr 24, 2002
Posts: 15
Hi Layne
Yes, you are right. I am also thinking that I should be using some Collection object and allocate the memory dynamically than using array of predefined size.
I remember reading somewhere that using Vector is not a good idea, I am not sure of the reason though. I am thinking of using ArrayList to hold my objects and sort it.
Appreciate your comments and if you have any suggestions, please do let me know.
Thanks
Kelly
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Jumping back a few days to comparing apples & oranges. I made the comment that objects don't have to be the same class to be comparable to each other because I spotted it in the doc.
If you had to compare the weight of apples and oranges you might push the comparison up to the fruit class. But if fruit already supports comparison on price, you might have to override compareTo on apple and orange.
Ok, seriously contrived, but it could happen! Plugable comparators would be an alternative to overriding.
[ April 02, 2003: Message edited by: Stan James ]
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Kelly KMoni:
I remember reading somewhere that using Vector is not a good idea, I am not sure of the reason though. [...]
The reason was that Vector is an older, effectively superseded class which pre-dates the Collections framework.
  • Retrofitting Vector with the List methods have made its API bloated and ambiguous. This is confusing especially in a team context; one developer might use iterator() where another uses elements().
  • Vector is synchronized. If you're not writing multi-threaded code, this just makes it slower.
  • If you are writing multi-threaded code, Vector's synchronization usually makes it slower too! The reason is that it's rarely the little Vector methods that need to be atomic w.r.t. other threads, but larger composite methods that you write.
  • In my experience, the misconceived notion that "Vector makes my code threadsafe" tends to lure developers inexperienced in concurrent programming into a false sense of security, and makes them more likely to write thread-unsafe code.
  • The Collections framework is a coherent and much more feature-complete set of interfaces and classes. The legacy collection classes, Vector, Hashtable and friends, are just excess baggage. If you need a synchronized List, use Collections.synchronizedList() on an ArrayList or LinkedList.
  • HTH,
    - Peter
    [ April 03, 2003: Message edited by: Peter den Haan ]
    Kelly KMoni
    Greenhorn

    Joined: Apr 24, 2002
    Posts: 15
    Thanks Peter for the wonderful explanation about Vector! I am able to understand now.
    Also, I was able to solve my problem with sorting last night. Like you guys suggested, I changed my code to use ArrayList to hold the objects and wrote classes which implements comparator for each sorting order. Everything works fine now, I am able to sort the objects!
    Like Peter correctly pointed out, my problem was null elements. Thanks a lot to all of you for the valuable suggestions and help.
    Regards
    Kelly
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Sorting collection of objects