gpt4 book ai didi

java - 如何将值从一个 Java 类复制到具有相同属性的另一个类

转载 作者:行者123 更新时间:2023-12-02 02:27:16 25 4
gpt4 key购买 nike

这是我的类结构:(省略了 getter 和 setter)

public class A { 
public List<QuestionTemplate> qTemplateList;
}

public class QuestionTemplate {
public List<QuestionList> qList;
}

public class QuestionList {
public String questionText;
public String questionChoice;
}

----------------------------------------------------

public class B {
public List<QuestionTemplate> qTemplateList;
}

public class QuestionTemplate {
public List<QuestionList> qList;
}

public class QuestionList {
public String questionText;
public String questionChoice;
}

我想手动将数据从B类复制到A类,手动复制字段而不是使用任何类型的映射器。

我尝试遍历列表并尝试从一个列表复制到另一个列表(从最里面的列表开始,但遇到了很多问题。请原谅,因为我是新手。我尝试过。请帮助。

最佳答案

此代码需要 Java 7 或更高版本。

选项 A 通过迭代手动复制数据:

    A a = new A();

..

List<QuestionTemplate> templateListCopy = new LinkedList<>();
for (QuestionTemplate template : a.qTemplateList) {
List<QuestionList> questionListCopy = new LinkedList<>();
for (QuestionList question : template.qList) {
QuestionList questionCopy = new QuestionList();
questionCopy.questionText = question.questionText;
questionCopy.questionChoice = question.questionChoice;
questionListCopy.add(questionCopy);
}
QuestionTemplate questionTemplateCopy = new QuestionTemplate();
questionTemplateCopy.qList = questionListCopy;
templateListCopy.add(questionTemplateCopy);
}
B b = new B();
b.qTemplateList = templateListCopy;

选项B 修改类并添加复制方法,以使实现代码更容易混淆:

class A {
public List<QuestionTemplate> qTemplateList;

public A copy() {
A copy = new A();
List<QuestionTemplate> questionTemplateListCopy = new ArrayList<>(qTemplateList.size());
for (QuestionTemplate questionTemplate : qTemplateList) {
questionTemplateListCopy.add(questionTemplate.copy());
}
copy.qTemplateList = questionTemplateListCopy;
return copy;
}
}

class QuestionTemplate {
public List<QuestionList> qList;

public QuestionTemplate copy() {
QuestionTemplate copy = new QuestionTemplate();
List<QuestionList> qListCopy = new ArrayList<>(qList.size());
for (QuestionList questionList : qList) {
qListCopy.add(questionList.copy());
}
copy.qList = qListCopy;
return copy;
}
}

class QuestionList {
public String questionText;
public String questionChoice;

public QuestionList copy() {
QuestionList copy = new QuestionList();
copy.questionText = questionText;
copy.questionChoice = questionChoice;
return copy;
}
}

实现:

A a = new A();

..

B b = new B();
b.qTemplateList = a.copy().qTemplateList;

关于java - 如何将值从一个 Java 类复制到具有相同属性的另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57246223/

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