2013-02-28 66 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

相关问题