Reputation: 49371
I am adding objects into a java Vector using its add(Object) method. In my example, the first 5 objects are identical, followed by 2 instances different from the first five. For some reasons, as soon as I insert the first one that is different, it changes the entire vector to that value!
'values' is an iterator containing something like '1','1','1','1','1','2','2'
Vector temp = new Vector();
while (values.hasNext()) {
temp.add(values.next());
System.out.println(temp.toString());
}
It will output something like
[1]
[1,1]
[1,1,1]
[1,1,1,1]
[1,1,1,1,1]
[2,2,2,2,2,2]
[2,2,2,2,2,2,2]
I tried using a LinkedList, as well as using add(object, index). Same thing happened.
Upvotes: 1
Views: 1677
Reputation: 19600
The following program compiled and ran under Mac OS X
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
public class Test{
public static void main( String ... args ){
List list = Arrays.asList(new String[] {"1","1","1","1","1","2","2"});
Iterator values = list.iterator();
Vector temp = new Vector();
while (values.hasNext()) {
temp.add(values.next());
System.out.println(temp.toString());
}
}
}
produced the following results:
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 2]
[1, 1, 1, 1, 1, 2, 2]
So you might want to provide the full implementation especially your Iterator. And I just have to say it, but you really shouldn't use Vector!
Upvotes: 2
Reputation: 269657
I suspect that, somehow, the "objects" you are getting from the iterator are really multiple references to a single instance of a mutable object, which is changing its state from "1" to "2". The thing I can't guess at is how it's changing state in this apparently single-threaded operation.
Can you post more complete code? Show where values
comes from and how it is initialized.
Upvotes: 10