簡體   English   中英

Java排序ArrayList <Integer>

[英]Java sorting ArrayList<Integer>

好吧,我有一些非常簡單的東西,但我無法弄清楚。

首先,我知道有Collection.sort()方法,但是我的ArrayList是對指向主對象的數據的鏈接的排序,並且需要根據該對象的數據進行排序。

像這樣的體育比賽, ArrayList<Integer> numbers將保持通過檢查點的參與者的數量。

我需要按照從最小到最大的最佳時間對該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;
    }

這不是實際的代碼,但是您已經有了主意。 我堅持嘗試尋找看似簡單的解決方案。 請幫忙

根據其他與您實際要排序的時間沒有直接關系的東西對ArrayList<Integer>進行排序似乎很尷尬。

我會設計不同。 看起來您已經定義了某種對象,可以在其上調用getTimeOfLastCheckPoint() 現在,我假設它稱為Participant 我將維護一個ArrayList<Participant> ,而不是維護ArrayList<Integer>來存儲對參與者的基於索引的引用。

然后,我將創建一個實現Comparator<Participant> (也許是ParticipantComparator )( Comparator javadocs )的類,該類知道如何基於對getTimeOfLastCheckPoint()的調用結果來比較Participant 然后排序就是Collections.sort(participantsArrayList, new ParticipantComparator());

編寫一個java.util.Comparator ,通過將Integer用作參與者數組中的索引來比較Integer

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對象,這些對象是參與者列表的索引,而不是Participant自身!

對我來說,這聽起來像是針對半成品SQL查詢的解決方法。 如果您的數據位於數據庫中(我很確定是這種情況),請修改您的SQL查詢,這樣您就不必在應用程序級別進行數據排序了。 這樣做的好處至少有兩個原因:

  1. 簡單應用邏輯
  2. 加快執行速度(數據庫可以更快地進行排序)

您可以使用Comparator根據比賽時間對列表進行排序,也可以使用Java中的for-each循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM