I have a problem of adding elements into an ArrayList. Each time I do the ‘add’, the entire array content is replaced with the current element value. I end up with eg. 10 repeated element duplicates.
The classes are set up as follows:
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.
}
Am I getting Java memory allocation confused here? It appears that EmployeeRow variable and the ArrayList are sharing the same memory space – very peculiar. Thanks guys
You are adding the same instance of the
EmployeeRowclass to the arraylist. Try something like: