http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts-based-on-name
60
47
|
Ok so I have a been making an addressbook application and have pretty much finished all the key features but I am looking to implement a sort feature in the program.
I want to sort an Arraylist which is of a type called Contact (contactArray) which is a separate class which contains four fields; name, home number, mobile number and address. So I was looking into using the collection sort yet am not sure how i'd implement this.
Is this the right sort I should be using / is it possible to use or should I look into making a custom sort?
| ||||
|
153
|
Here's a tutorial about ordering objects:
Although I will give some examples, I would recommend to read it anyway.
There are various way to sort an
ArrayList . If you want to define a natural (default) ordering, then you need to let Contact implement Comparable . Assuming that you want to sort by default on name , then do (nullchecks omitted for simplicity):
so that you can just do
If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a
Comparator :
You can even define the
Comparator s in the Contact itself so that you can reuse them instead of recreating them everytime:
which can be used as follows:
And to cream the top off, you could consider to use a generic javabean comparator:
which you can use as follows:
(as you see in the code, possibly null fields are already covered to avoid NPE's during sort)
| ||||||||||||||||||||
|
6
|
This page tells you all you need to know about sorting collections, such as ArrayList.
Basically you need to
There's another way as well, involving creating a Comparator class, and you can read about that from the linked page as well.
Example:
|