2013-11-22 147 views
0

那麼,我的股票非常簡單,但我無法弄清楚。Java排序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; 
    } 

這不是實際的代碼,但你有想法。我堅持嘗試尋找看似簡單的解決方案。 請幫助

回答

0

您可以使用Comparator根據其競賽持續時間對列表進行排序,並且還可以使用for-each循環在Java中。

3

基於其他與你實際想要排序的東西 - 時間沒有直接關係的東西,排序ArrayList<Integer>似乎很尷尬。

我會對它進行不同的設計。看起來你有一些定義的對象,你可以調用getTimeOfLastCheckPoint()。現在,我假設它叫做Participant。我會保留ArrayList<Participant>,而不是維護ArrayList<Integer>來存儲基於索引的參考。

然後我會創建一個實現Comparator<Participant>知道如何根據調用getTimeOfLastCheckPoint()的結果進行比較Participant個類(也許ParticipantComparator)(Comparator javadocs)。然後排序只是Collections.sort(participantsArrayList, new ParticipantComparator());

+0

此ArrayList 我給我的自定義ListAdapter這從這些數字中提取大量數據。就像我將ArrayList 號碼傳遞給適配器,並在此參數名稱下設置了List參與者的名稱,他的名字,團隊等等。我有的根對象是Competition,它有一個列表,例如150個參與者對象,其中有關時間的數據等等。所以我不會將大量數據傳遞給適配器,只有鏈接到我的ArrayList user2976267

3

java.util.Comparator,通過使用它們作爲你參加陣列在指數比Integer S:

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

2

對我來說,這聽起來像是一個解決方案,用於完成一半的SQL查詢。如果您的數據駐留在數據庫中(並且我確信情況如此),請修改您的SQL查詢,以便您不必在應用程序級別對數據進行排序。這是好事,至少有兩個方面的原因:

  1. Simplyfiy應用邏輯
  2. 加快執行速度(該數據庫可以做這樣的排序更快)