Search code examples
javavectortype-2-dimension

Java add 1D vector to 2D vector


I got a problem when I tried to add 1D vector to 2D vector.

I wrote specific codes as following

Vector<Vector<String>> multiVector = new Vector<Vector<String>>();
Vector<String> singleVector = new Vector<String>();

singleVector.add("a,a,a");                      
System.out.println(singleVector);               // [a,a,a]
multiVector.add(singleVector);                  
System.out.println(multiVector);                // [[a,a,a]]
singleVector.clear();                         
singleVector.add("b,b,b");                      
System.out.println(singleVector);               // [b,b,b]
multiVector.add(singleVector);                  
System.out.println(multiVector);                // [[b,b,b], [b,b,b]]

At the last line, I expected that "[[a,a,a], [b,b,b]]" but the result was "[[b,b,b], [b,b,b]]"

What is wrong ?

Thanks in advance.


Solution

  • When you're adding the singleVector object to multiVector, you're not making a copy of it. So when you clear the singleVector and change it to "b,b,b" you're also "changing" the (same) object that you added to multiVector.

    If you want to change singleVector without modifying multiVector you should singleVector = new Vector<>() instead of clear()'ing it.