I am looking to implement a sort feature for my address book application.
I want to sort an ArrayList<Contact> contactArray. Contact is a class which contains four fields: name, home number, mobile number and address. I want to sort on name.
How can I write a custom sort function to do this?
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 letContactimplementComparable. Assuming that you want to sort by default onname, 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
Comparators in theContactitself 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)