• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting collection of objects

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Kelly KMoni
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Do you have any null elements in your array?
- Peter
 
Kelly KMoni
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Kelly KMoni
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
    Posts: 15
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
     
    Consider Paul's rocket mass heater.
    reply
      Bookmark Topic Watch Topic
    • New Topic