gpt4 book ai didi

java - 将java列表转换为对象

转载 作者:行者123 更新时间:2023-12-01 09:48:08 24 4
gpt4 key购买 nike

我必须将包含一些字符串的列表转换为 java 对象,这是列表:

[099882, 11, 6, 0, 25]

这个列表的每个位置代表一个java类中的一个字段,这是这个类:

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;
}

}

我就这样填写列表:

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);
}

有什么想法吗?

最佳答案

也许您可以在构造函数的签名中使用数组,而不是列出所有字段:

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];
}
}

您甚至还可以使用数组来保存 Chunk 的字段:

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

无论哪种方式,另一段代码只需要向 Chunk 的构造函数提供字符串数组: int[] fileSplits = {6,2,1,1,2}; int 总计 = 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);

您当然应该添加一些验证,以确保在 Chunk 的构造函数中不会抛出 ArrayOutOfBoundException。

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];
}

关于java - 将java列表转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com