We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › how to sort ArrayList based on its objects
Page Index Toggle Pages: 1
how to sort ArrayList based on its objects? (Read 798 times)
how to sort ArrayList based on its objects?
Feb 22nd, 2009, 8:13am
 
I have an ArrayList with custom objects in them.  How do I sort the list by the contents of one variable in the objects?  e.g. objects are of class TimePoint() with properties .time and .type.  i want to sort the ArrayList of TimePoints by time.


Re: how to sort ArrayList based on its objects?
Reply #1 - Feb 22nd, 2009, 9:28am
 
There are several ways to do this:

(1) Override the compateTo method or and use Collections.sort(<List>)

(2) Write a Comparator [1] and override the equals method and use Collections.sort(<List>, <Comparator>) [2]

If you want to use data types, which uses the hashCode method (like HashSet/HashMap), you should take care to be consistent with the hashCode method [3].

Some links:
[1] http://java.sun.com/javase/6/docs/api/java/util/Comparator.html
[2] http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29
[3] http://www.geocities.com/technofundo/tech/java/equalhash.html
Re: how to sort ArrayList based on its objects?
Reply #2 - Feb 22nd, 2009, 10:26am
 
See also sort array of objects by String inside variable thread.
Principles are the same for arrays and collections.
Re: how to sort ArrayList based on its objects?
Reply #3 - Feb 23rd, 2009, 2:08am
 
thanks both, option 1 and that referenced thread did the job quickly.  will read those docs someday...


Page Index Toggle Pages: 1