java - 字母顺序(列表)

发布于 2024-10-08 16:06:45 字数 266 浏览 1 评论 0原文

可能的重复:
按字母顺序对列表进行排序

我如何按字母顺序存储输入,我正在将名称输入到数组列表中:

    persons.add(person);

如何这样做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

捂风挽笑 2024-10-15 16:06:45

实现比较器< T > 接口

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;
    }

}

,然后使用 Collections.sort(/* 这里列出 */, /* 这里比较器 */)

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

裂开嘴轻声笑有多痛 2024-10-15 16:06:45

试试这个:

 java.util.Collections.sort(people);

Try this:

 java.util.Collections.sort(people);
无妨# 2024-10-15 16:06:45
Collection<Person> listPeople = new ArrayList<Person>();

Person.java 类将实现 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;
 }

}

一旦你有了这个,在你要添加人员的类中,当你完成添加后,输入:

Collections.sort(listPeople);
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);
吃→可爱长大的 2024-10-15 16:06:45

使用TreeSet代替ArrayList

use TreeSet instead of ArrayList

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文