Reputation: 577
I have the code:
private class Record {
byte year;
float val;
}
Record record=new Record();
List<Record> recList = new ArrayList<Record>();
...
//now I add first element to array list
record.year=12;
record.val=55;
recList.add(record);
//now I add second element to array list
record.year=13;
record.val=77;
recList.add(record);
As you see I add different elements. But as a result all elements in array list are the same. So adding 2-nd, 3-d... element changes all previous elements to the values of last "record". What's wrong? Thanks?
Upvotes: 0
Views: 52
Reputation: 124215
As you see I add different elements
No, you just edited old Record
object and added it again. Each time before you add Record
object you need to crate new
one.
Upvotes: 1
Reputation: 12266
You need to instantiate new objects so they are physically different objects. Right now, you only have one object that is in the ArrayList multiple times.
Record record = new Record();
Also, you should add hashCode() and equals() to Record since you are working with collections.
Upvotes: 1
Reputation: 44439
An ArrayList
keeps a list of references to objects. You're always modifying the same original object which means the reference is the same, but its values differ.
You can fix it by explicitly assigning a new instance to the record
variable:
record.year=12;
record.val=55;
recList.add(record);
record = new Record();
record.year=13;
record.val=77;
recList.add(record);
Upvotes: 3