2013-02-28 92 views
0

我正在讀取名爲「Holder」的自定義對象的分隔文件。 Holder包含名爲「Record」的自定義對象列表。每個記錄都包含稱爲「字段」的自定義對象。每個字段都有一個字符串名稱和字符串值按java中子列表中的屬性對列表排序

public class Holder{ 
    private List RecordList; 
    /* constructors and methods */ 
} 

public class Record{ 
    private List FieldList 
    /* constructors and methods */ 
} 

public class Field{ 
    private String Name; 
    private String Value; 
    /* constructors and methods */ 
} 

我拉名稱從基於上線的第一個項目一個數據庫中的字段對象。 這裏是我拉的文件的樣本(行號 - 他們也可以記錄索引 - 從0開始增加,爲了便於說明):

0 - A,123 
1 - B,123,123456 
2 - B,123,654321 
3 - B,123,112233 
4 - C,123,choice1,1/1/2011,12/31/2011 
5 - C,123,choice2,1/1/2011,12/31/2011 
6 - D,123,choice1,1/1/2011,12/31/2011,654321 
7 - D,123,choice1,1/1/2011,12/31/2011,112233 

持證人在商店Record對象的列表。每一行成爲一個Record對象,該對象存儲一個Field對象的列表。逗號之間的每個字符串在Field對象上成爲它自己的Value。 例:對於第一個「B」的記錄(1號線),A Record BLine1物體看起來像:

BLine1.getFieldList.get(0).getName() = "LineType" //set from DAO not shown 
BLine1.getFieldList.get(0).getValue() = "B" 

BLine1.getFieldList.get(1).getName() = "Number" //set from DAO not shown 
BLine1.getFieldList.get(1).getValue() = "123" 

BLine1.getFieldList.get(2).getName() = "Selection" //set from DAO not shown 
BLine1.getFieldList.get(2).getValue() = "123456" 

我需要排序這個列表中的每個字段。但根據LineType的不同,要排序的項目類型和數量也會發生變化。 LineTypes可以添加/刪除,並且字段可以更改。所以我真的需要一些儘可能通用的東西。

它將按照字段順序排列。所以它會通過FieldList.getValue(0), FieldList.getValue(1), .... FieldList.getValue(FieldList.size() - 1)

所以進行排序,這是爲了當它完成了行號應該是:

0 
3 
1 
2 
4 
5 
7 
6 

什麼做這樣的最佳/最有效的方法是什麼?

在此先感謝!

回答

1

忽略空的所有可能性,這個怎麼樣了Comparator<Record>

public int compare(Record r1, Record r2) { 
    // if one field list is longer than the other treat that one as greater 
    int lenDiff = r1.getFieldList().size() - r2.getFieldList().size(); 
    if(lenDiff != 0) return lenDiff; 

    // both field lists same length, do lexicographic comparison 
    Iterator<Field> it1 = r1.getFieldList().iterator(); 
    Iterator<Field> it2 = r2.getFieldList().iterator(); 
    while(it1.hasNext()) { 
    Field f1 = it1.next(); 
    Field f2 = it2.next(); 
    int diff = f1.getValue().compareTo(f2.getValue()); 
    if(diff != 0) return diff; 
    } 

    // all components equal, so both lists equal. 
    return 0; 
} 

您可以用Collections.sort使用。

顯然,如果你可能有一個null記錄,或用null字段的記錄,或現場與null值,那麼這一切得到而較爲凌亂......

+0

與lenDiff第一部分將不必然有效,因爲後來的一些類型比以前的類型短。沒有在問題中說明我的錯。 我會在週末嘗試一下,並報告回來。它看起來像我想要的。謝謝! – AgentBawls 2013-03-01 15:26:26