Reputation: 1602
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
Upvotes: 1
Views: 286
Reputation:
Only one EmployeeRow object is every created.
Then it is modified. "It" being "the same object". If a new object is desired, then create a new object :)
Happy coding.
Upvotes: 2
Reputation: 1328
You aren't creating new rows so every element is the same and since the loop ends at ten the last object has a value of ten.
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 = new EmployeeRow();
_empRow.EmpNum = x; // etc for other variable in EmployeeRow
_bradfordData.add(er);
}
}
// THE RESULT IN _bradfordData is 10 elements, all with EmpNum = 10!
}
Upvotes: 1
Reputation: 10417
You are adding the same instance of the EmployeeRow
class to the arraylist. Try something like:
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.
}
Upvotes: 4
Reputation: 43504
Yes when you do
_empRow.EmpNum = x;
you are changing the objects internal variable. You need to construct a new object each time. Inside the loop do something like this:
EmployeeRow _empRow = new EmployeeRow();
_empRow.EmpNum = x;
_bradfordData.add(_empRow);
Upvotes: 1