为什么我的vector.add将字符串添加到所有外部Vector <vector <string>&gt;

时间:2016-04-30 22:02:20

标签: java vector

对于java vector操作,get和add,我对我的测试结果感到困惑:

public class temp {
private static Vector<Vector<String>> elems;
public static void main(String args[]) {
    int bucketCount = 5;
    elems = new Vector<Vector<String>>(bucketCount);
    int pos = 4;
    String s ="world";

    int elemsSize = elems.size();
    if ( pos >= elemsSize) //grow the outer vector
    {
        Vector<String> empty = new Vector<String>(Arrays.asList(""));
        for (int i = 0; i<= pos; i++) elems.add(i,empty);
    }

    //APPROACH -1
    Vector<String> v1 = new Vector<String>();
    System.out.println(v1);
    v1= (Vector<String>) elems.get(pos).clone();
    v1.add(0,s);//this does what i want
    System.out.println(v1);
    elems.set(pos, v1);
    System.out.println(elems);
    }
}

以上方法我是我真正想要实现的,它确实有效:

     []
     [world, ]
     [[], [], [], [], [world, ]]

如果我将方法1更改为接近2,则以某种方式将字符串添加到所有外部向量,为什么输出如下所示:

    []
    [world, ]
    [[world, ], [world, ], [world, ], [world, ], [world, ]]

APPROACH - 2代码:

    //I thought I am pointing to the 4th outer element by using the elems.get
    Vector<String> l2 = elems.get(pos); 
    System.out.println(l2);
    l2.add(0,s);
    System.out.println(l2);
    elems.set(pos, l2);
    System.out.println(elems);

    //TODO: why the add somehow add the string to all indexes? 
    //even though it was a pointer, it shall point to the right place

0 个答案:

没有答案