There are two ways to do this.
In this approach, you sort the ArrayList
using a custom Comparator
.
Here is the Comparator
code. Notice how it first tries to sort on numberType
, and then number
:
public class PhoneNumberComparator implements Comparator<PhoneNumber> {
@Override
public int compareTo (PhoneNumber lhs, PhoneNumber rhs) {
int result = lhs.numberType.compareTo(rhs.numberType);
if (result == 0) {
result = lhs.number.compareTo(rhs.number);
}
return result;
}
}
Then you can call:
Comparator c = new PhoneNumberComparator();
arrayListToSort.sort (c)
Now by itself, this won't work completely because the sort of numberType
will just be in string order. The most convenient way to impose the ordering is to make numberType
an enumeration. Here is the code for that:
public enum NumberType { MOBILE, HOME, OFFICE }
Then the PhoneNumber
must be defined so that numberType
is a NumberType
:
public class PhoneNumber {
public String number ;
public NumberType numberType;
// .......
}
(By the way I would encourage you to also make number
and numberType
into private
variables, and add getter methods, as per the JavaBeans standard.)
Make PhoneNumber
Implement Comparable
If you are planning to do this sort often, then instead of writing the Comparator
, you should make PhoneNumber
implement the Comparable
interface:
public class PhoneNumber implements Comparable <PhoneNumber> {
public String number ;
public NumberType numberType;
// .......
@Override
public int compareTo (PhoneNumber rhs) {
int result = this.numberType.compareTo(rhs.numberType);
if (result == 0) {
result = this.number.compareTo(rhs.number);
}
return result;
}
}
Then you can just call:
arrayList.sort()
You still need to make NumberType
an enum
, as discussed in the first approach. The above compareTo()
implementation relies on NumberType
being Comparable
; all enum
instances are automatically Comparable
.
Notice the similarities and the differences between the Comparator
and the compareTo()
implementations. A good discussion of Comparator
and Comparable
can be found here.