Sorting an ArrayList
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Sebastian_Beyer
Posted On:   Wednesday, January 29, 2003 02:27 AM

Hi Gurus,

I have several ArrayLists containing Java Beans. Now I want to have the List to be sorted by the methods JavaBean.getId(). This method is always named the same in the different Beans, but I could not find a way to let my Lists be sorted. I could write my own BubbleSort, but isnt there structure, providing this?


Greetings from Hamburg/Germany


Seppo

Re: Sorting an ArrayList

Posted By:   Stephen_McConnell  
Posted On:   Wednesday, January 29, 2003 04:56 AM

One of the cool things about the Collections API's is you can use the static method in the java.util.Collections class to sort an ArrayList.


You need to create a class that implements the java.util.Comparator interface. It has two methods compare(Object a, Object b) and equals(Object a) that need to be implemented. You write the code that
does the type of comparison you need and then call the static method on java.util.Collections.sort(List list, Comparator compClass); and it will do your sort for you. ArrayList extends the List interface, so you are ok there.


Check out the JavaDoc for these classes for specifics and a basic example.


Hope this helps


Stephen McConnell

About | Sitemap | Contact