Possible Duplicate:
Sort List Alphabetically
how do i store my inputs in alphabetical order, i am inputting names into an arraylist:
persons.add(person);
How to do that?
Gerhard Presser
Try this:
java.util.Collections.sort(people);
implements Comparator< T >
interface
class A implements Comparator < Person > {
@Override
public int compare(Person o1, Person o2) {
if(o1.getName() != null && o2.getName() != null){
return o1.getName().compareTo(o2.getName());
}
return 0;
}
}
then use Collections.sort(/* list here */, /* comparator here*/)
Collection<Person> listPeople = new ArrayList<Person>();
The class Person.java will implements Comparable
public class Person implements Comparable<Person>{
public int compareTo(Person person) {
if(this.name != null && person.name != null){
return this.name.compareToIgnoreCase(person.name);
}
return 0;
}
}
Once you have this, in the class you're adding people, when you're done adding, type:
Collections.sort(listPeople);
use TreeSet instead of ArrayList
来源:https://stackoverflow.com/questions/4518997/java-alphabetical-order-list