Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

sorting the Arraylist elements  RSS feed

 
lakshmi v.samy
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

can anybody help me?

I want to sort the array list elements in ascending order.Please tell me simple logic.

Thanks in advance.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Collections.sort is your friend

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it really depends on what kind of objects are you storing, and how should they be compared, how do you tell which objects are the same, or which should come before or after another.

If you're storing String objects and can sort by the normal English natural order, Collections.sort is fine. If not, you should implement your object's equals & hashCode methods to aid in the sorting.

Check out the book Effective Java for more detail information.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chengwei Lee:
Well, it really depends on what kind of objects are you storing, and how should they be compared, how do you tell which objects are the same, or which should come before or after another.

If you're storing String objects and can sort by the normal English natural order, Collections.sort is fine. If not, you should implement your object's equals & hashCode methods to aid in the sorting.

Check out the book Effective Java for more detail information.


Effective Java is a good book, but you must be thinking of something else, because sorting doesn't use equals or hashCode. If the elements in the list are mutually Comparable, you can use the sort:

This uses the element's compareTo method. And in any case, you can sort with a Comparator:

This uses the comparator's compareTo method. In neither case are the element's equals or hasCode methods called.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!