请问以下代码的输出是什么?为什么?import java.util.Arrays;
import java.util.Vector;public class TestSort
{
    public static void main(String[] args)
    {
        int[] a = new int[2];
        Vector<int[]> v = new Vector<int[]>(1);
        Arrays.fill(a, 1);
        v.add(a);        for (int[] i : v)
        {
            for (int j : i)
            {
                System.out.println(j);
            }
        }
        System.out.println("-----------------------");        Arrays.fill(a, 2);
        v.add(a);        for (int[] i : v)
        {
            for (int j : i)
            {
                System.out.println(j);
            }
        }
        System.out.println("-----------------------");        Arrays.fill(a, 3);
        v.add(a);
        Arrays.fill(a, 4);
        v.add(a);
        Arrays.fill(a, 5);
        v.add(a);        for (int[] i : v)
        {
            for (int j : i)
            {
                System.out.println(j);
            }
        }
    }}为什么
Arrays.fill(a, 5);
v.add(a);
这样以后整个Vector的内容都变成了5?

解决方案 »

  1.   

    因为你都是用v.add(a);加数据的,所以这些引用都指向同一个地方
      

  2.   

    LZ现在这个Vector都已经不推荐使用了
    呵呵
    不过问题应该还是要弄清楚滴啊!
      

  3.   

    唉,从jdk6的doc来看,只有这些说明,在我看来,既然是Appened了,就应该是在原来的基础上向尾部增加啊。
    add
    public boolean add(E e)Appends the specified element to the end of this Vector. Specified by:
    add in interface Collection<E>
    Specified by:
    add in interface List<E>
    Overrides:
    add in class AbstractList<E>
    Parameters:
    e - element to be appended to this Vector 
    Returns:
    true (as specified by Collection.add(E))
    Since: 
    1.2 
    如果不用这个Vector,那该用什么呢?
      

  4.   

    看来还是得自己来:不管是Vector还是ArrayList,add方法都只是把对象的引用放到了Vector或ArrayList中,而不是新建了一个对象。所以第2次add的时候,Vector对象中实际上保存了两份指向同一个对象的引用,于是把被指向的对象更改以后,Vector中所有的数据都更新了。