简体   繁体   中英

Transform a java list to object

I have to transform a list containing some strings to a java object, this is the list:

[099882, 11, 6, 0, 25]

Each position of this list represents a field in a java class, this is the class:

public class Chunks extends BaseModel {
    private static final long serialVersionUID = 1494042139468968199L;

    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;

    public Chunks(String field1, String field2, String field3, String field4, String field5) {
         this.field1 = field1;
         this.field2 = field2;
         this.field3 = field3;
         this.field4 = field4;
         this.field5 = field5;
    }   

}

i fill the list just like that:

private static void splitFile(Path path){
    int[] fileSplits = {6,2,1,1,2};
    int total = 0;

    List<String> stringList = new ArrayList<String>();
    for (int i = 0 ; i < fileSplits.length ; i++) {
        stringList.add(path.toString().substring(total, total+=fileSplits[i]));
    }

    // Have to transform the list just right here !!!
    //      and then..
    //          dbInsert(convertedObject);
}

Any idea?

Perhaps you could use an array in the Constructor's signature, instead of listing all fields:

public class Chunk{
    private static final long serialVersionUID = 1494042139468968199L;

    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;

    public Chunk(String[] fields) {
         this.field1 = fields[0];
         this.field2 = fields[1];
         this.field3 = fields[2];
         this.field4 = fields[3];
         this.field5 = fields[4];
    } 
}

You could also even use an array to hold Chunk's fields:

public Chunk(String[] fields) {
        this.fields = fields;
    } 

Either way, the other piece of code simply needs to provide the array of string to Chunk's constructor: int[] fileSplits = {6,2,1,1,2}; int total = 0;

    String[] stringList = new String[fileSplits.length];
    for (int i = 0 ; i < fileSplits.length ; i++) {
       stringList = path.toString().substring(total, total+=fileSplits[i]);
    }

    Chunk chunk = new Chunk(stringList);

You should certainly add a few validations to ensure that an ArrayOutOfBoundException isn't thrown in Chunk's constructor..

public Chunk(String[] fields) {
    if(fields==null || fields.length<5){
        throw new SomeException();
    }
    this.field1 = fields[0];
    this.field2 = fields[1];
    this.field3 = fields[2];
    this.field4 = fields[3];
    this.field5 = fields[4];
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM