Problem with lists (java.util)
I have a problem with a list I'm working with. I initialize the list pretty simply
List<Type> list = new LinkedList<Type>();
Then I add stuff to an object, then add the object to the list.
list.add(object);
This .add() is in a while loop, and a new object is added each time, however the list does not behave as such. Given elements 1,2,3,4,5 in order it will compose the list like this:
1
22
333
4444
55555
So in the end I have a list of the last element the total number of elements times. I only create the list, then add to it, any reason why this would be happening?
[651 byte] By [
DBHa] at [2007-11-27 10:07:12]

Here is the code
List<IdentAddress> addresses = new LinkedList<IdentAddress>();
IdentAddress ia = new IdentAddress();
try{
scan = new Scanner(input[x]);
}catch(FileNotFoundException e){
System.out.println(e.getMessage());
}
int counter = 0;
while(scan.hasNext()){
line = scan.nextLine().split("\\|");
if(line[3] != null){
ia.setReporteddate(line[3]);
}else{
ia.setReporteddate(line[4]);
}
addresses.add(ia);
counter++;
}
DBHa at 2007-7-13 0:43:30 >

> addresses.add(ia);
This does not copy the object pointed to by ia. It simply gives addresses a copy of the reference to that single object pointed to by ia. You're only ever creating that one object.
This is always how it is with parameter passing and reference variable assignment in Java. To create a new object, you need new, or newInstance(), or clone().