I am writing a phonebook program in java and i need to list people in the list alphabetically and to do that i need to write a sorting algorithm for a list in java and it sh
As everyone else has mentioned, compareTo is part of the Comparable interface.
How you implement it depends on whether you want to order by surname or name first and if you want them sorted ascending order.
For example, if you want to order by surname first, in ascending order:
public class Person implements Comparable {
// the parts of Person you already have would go here
public int compareTo(Person person) {
if (person == null) {
return -1;
}
if (surname != null && person.getSur() == null) {
return -1;
} else if (surname == null && person.getSur() != null) {
return 1;
} else if (surname != null && person.getSur() != null) {
int compare = surname.compareToIgnoreCase(person.getSur());
if (compare != 0) {
return compare;
}
}
// Note that we did nothing if both surnames were null or equal
if (name == null && person.getName() == null) {
return 0;
} else if (name != null && person.getName() == null) {
return -1;
} else if (name == null && person.getName() != null) {
return 1;
} else {
return name.compareToIgnoreCase(person.getName());
}
}
}
(I didn't actually test this code)
This relies on String's implementation of compareToIgnoreCase.
Note that this also moves all null objects and objects with null names and surnames to the end of the list.
Having said all that, if you implement Comparable, you can make the Collections API do the work for you using sort.
If you find that you need multiple different sort methods for an object, you can create a set of Comparator objects to do the sorting instead.