【问题标题】:Java sorting ArrayList<Integer>Java 排序 ArrayList<Integer>
【发布时间】:2013-11-22 17:39:34
【问题描述】:

嗯,我有一些非常简单的东西,但我想不通。

首先,我知道有Collection.sort()方法,但是我的ArrayList是一种指向主对象的数据链接,我的排序需要根据这个对象的数据进行。

就像这是一场体育比赛,ArrayList&lt;Integer&gt; numbers 保存着通过检查站的参与者数量。

我需要按从 min 到 max 的最佳时间对这个 ArrayList 进行排序,以将它们设置为第一名、第二名等。

为此,我应该问我的竞争对象:

    public ArrayList<Integer> sort (ArrayList<Integer> numbers)
    for (int i=0;i<numbers.size){
    long time = competition.participant.get(numbers.get(i)).getTimeOfLastCheckPoint();
    /*Do something to make another ArrayList<Integer> sortedArray
 where all this will be sorted by this time parameter from minimal to maximum*/
    return sortedArray;
    }

这不是实际的代码,但你已经明白了。我坚持试图找到看似简单的解决方案。 请帮忙

【问题讨论】:

    标签: java android sorting arraylist


    【解决方案1】:

    根据与您实际想要排序的时间没有直接关系的其他事物对ArrayList&lt;Integer&gt; 进行排序似乎很尴尬。

    我会以不同的方式设计它。看起来您定义了某种对象,您可以在其上调用getTimeOfLastCheckPoint()。现在,我假设它被称为Participant。我不会维护ArrayList&lt;Integer&gt; 来存储对参与者的基于索引的引用,而是维护ArrayList&lt;Participant&gt;

    然后我将创建一个实现Comparator&lt;Participant&gt;(可能是ParticipantComparator)(Comparator javadocs)的类,它知道如何根据对getTimeOfLastCheckPoint()的调用结果来比较Participants。那么排序就是Collections.sort(participantsArrayList, new ParticipantComparator());

    【讨论】:

    • this ArrayList 我给了我的自定义 ListAdapter,它从这些数字中提取了大量数据。就像我将 ArrayList 数字传递给适配器,并在此数字下设置参与者的姓名、他的姓名、团队等。我拥有的根对象是竞争,它有一个列表,例如 150 个参与者对象的数据大约时间,等等。所以我不会将大量数据传递给适配器,只在我的 ArrayList 中链接到它们
    【解决方案2】:

    编写一个java.util.Comparator,将Integers 用作您的参与者数组中的索引来比较它们:

    public class ParticipantIndexComparator implements Comparator<Integer> {
        final List<Participant> participants;
        public ParticipantIndexComparator(List<Participant> participants) {
            this.participants = participants;
        }
    
        @Override
        public int compare(Integer i1, Integer i2) {
            long l1 = participants.get(i1).getTimeOfLastCheckPoint();
            long l2 = participants.get(i2).getTimeOfLastCheckPoint();
            return Long.compare(l1, l2);
        }
    }
    

    现在您可以使用此比较器对整数进行排序:

    Collections.sort(numbers, new ParticipantIndexComparator(participants));
    

    但在这样做之前,问问自己为什么您的列表包含作为参与者列表索引的Integer-objects,而不是Participants 本身!

    【讨论】:

      【解决方案3】:

      对我来说,这听起来像是半完成 SQL 查询的变通解决方案。如果您的数据驻留在数据库中(我很确定就是这种情况),请修改您的 SQL 查询,这样您就不必在应用程序级别对数据进行排序。这至少有两个原因:

      1. 简化应用程序逻辑
      2. 加快执行速度(数据库可以更快地进行这种排序)

      【讨论】:

        【解决方案4】:

        您可以使用Comparator 根据他们的比赛持续时间对列表进行排序,也可以在 Java 中使用 for-each 循环。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多