问题
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?
回答1:
Try this:
java.util.Collections.sort(people);
回答2:
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*/)
回答3:
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);
回答4:
use TreeSet instead of ArrayList
来源:https://stackoverflow.com/questions/4518997/java-alphabetical-order-list