开发者

java - alphabetical order (list) [duplicate]

This question already has answers here: Closed 10 years ago.

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?


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*/)


Try this:

 java.util.Collections.sort(people);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜