gpt4 book ai didi

Java内存空间重叠?

转载 作者:行者123 更新时间:2023-11-29 10:20:27 26 4
gpt4 key购买 nike

我在将元素添加到 ArrayList 时遇到了问题。每次我执行“添加”时,整个数组内容都会替换为当前元素值。我最终得到了例如。 10 个重复的元素副本。

类(class)设置如下:

public class BradfordReport {
EmployeeRow _empRow = new EmployeeRow();
ArrayList<EmployeeRow> _bradfordData = new ArrayList<EmployeeRow>();

public void Run() {
// processing to setup Employee row variables
for (int x=0; x<10; x++) {
// This next line in debug IS ADJUSTING THE ARRAYLIST DATA!!
_empRow.EmpNum = x; // etc for other variable in EmployeeRow
_bradfordData.add(er);
}
}
// THE RESULT IN _bradfordData is 10 elements, all with EmpNum = 10!
}

public class EmployeeRow {
int EmpNum;
string EmpNm; // etc.
}

我在这里混淆了 Java 内存分配吗? EmployeeRow 变量和 ArrayList 似乎共享相同的内存空间 - 非常奇特。谢谢大家

最佳答案

您正在将 EmployeeRow 类的相同实例添加到数组列表中。尝试类似的东西:

public class BradfordReport {
EmployeeRow _empRow = new EmployeeRow();
ArrayList<EmployeeRow> _bradfordData = new ArrayList<EmployeeRow>();

public void Run() {
// processing to setup Employee row variables
for (int x=0; x<10; x++) {
// create a NEW INSTANCE of an EmployeeRow
_empRow = new EmployeeRow();
_empRow.EmpNum = x; // etc for other variable in EmployeeRow
_bradfordData.add(_empRow);
}
}
// THE RESULT IN _bradfordData is 10 elements, all with EmpNum = 10!
}

public class EmployeeRow {
int EmpNum;
string EmpNm; // etc.
}

关于Java内存空间重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7200076/

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