Why is my add method overwriting the vector?

I am adding objects to a java vector using its add (Object) method. In my example, the first 5 objects are identical, followed by 2 instances other than the first five. For some reason, as soon as I insert the first one, which 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 LinkedList and also using add (object, index). The same thing happened.

+1


source to share


2 answers


I suspect that somehow the "objects" you get from the iterator are indeed multiple references to a single mutable object instance that changes its state from "1" to "2". I can't guess how this changed in this seemingly single-threaded operation.



Can you post a more complete code? Show where and where it is initialized from values

.

+10


source


The following program compiled and run 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]

      

This way you can provide a complete implementation, especially your Iterator. And I just have to say this, but you really shouldn't be using Vector!

+2


source







All Articles