How to make compareTo sort a list alphabetically?
How do I change my code so that it lists the elements in alphabetical order from a to z. Right now it's ordering from z to a. I can't figure it out and am stuck :-/
String s开发者_运维技巧Name1 = ((Address)o).getSurname().toLowerCase();
String sName2 = (this.surname).toLowerCase();
int result = (sName1).compareTo(sName2);
return result;
Thanks :)
Just swap the objects you're comparing.
int result = (sName2).compareTo(sName1);
Usually, for ascending sorting you'd like the lefthand side be part of this object and the righthand side be part of the other object. For descending sorting you just swap the both sides (which you thus initially did).
To make your code more intuitive, I'd however rather swap the assignments of sName1
and sName2
:
String sName1 = (this.surname).toLowerCase();
String sName2 = ((Address)o).getSurname().toLowerCase();
int result = (sName1).compareTo(sName2);
And get rid of the hungarian notation and unnecessary parentheses as well. The following sums it:
public class Address implements Comparable<Address> {
private String surname;
// ...
public int compareTo(Address other) {
return this.surname.toLowerCase().compareTo(other.surname.toLowerCase());
}
}
You may want to add nullchecks if you can't guarantee that surname is never null
.
See also:
- Object Ordering tutorial at Sun.com
- Different ways to sort a list of Javabeans
精彩评论