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<Person> {
// 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.
You can make your Person
class implement Comparable
, and define the following method:
public class Person implements Comparable<Person> {
// Your previous code
public int compareTo(Person other) {
if (other == null) {
// throw exception for example
}
return this.name.toLowerCase().compareTo(other.name.toLowerCase());
}
}
The Person class' signature should be like this:
public class Person implements Comparable<Person>
Add compareTo-method to Person class and use Collections.sort(personList) as starf suggested.
Implement Comparable
in your Person class.
Your compareTo() method would then be something like:
public int compareTo(Person other) {
return name.compareTo(other.getName())
}
Then use Collections.sort(<your list of Person>);