首页 新闻 会员 周边

二维vector中,get()方法的返回值问题。

0
悬赏园豆:10 [已解决问题] 解决于 2014-05-16 23:09

先上代码:

public static void main(String[] args) {
Vector<Vector<Integer>> v = new Vector<Vector<Integer>>();
Vector<Integer> c = new Vector<Integer>();
c.add(1);
c.add(2);
c.add(3);
v.add(c);
System.out.println(v);

c = v.get(0);
c.remove(1);
System.out.println(v);
}

结果是:

[[1, 2, 3]]
[[1, 3]]

我的困惑是:既然get返回的c是一个vector值而不是指针,对c的修改怎么会改变向量集v的哪?

一直爬行的蜗牛的主页 一直爬行的蜗牛 | 初学一级 | 园豆:193
提问于:2014-05-14 17:14
< >
分享
最佳答案
0

java中的对象, 除非再次调用了一个new, 否则所表示的内容都是相同的, 也就是说:

v.add(c), 将c添加到了v中, 并不是重新进行了new, 因此, v中c和c本身表示的都是同一内存中的内容。

如下图:

收获园豆:10
grassofsky | 菜鸟二级 |园豆:342 | 2014-05-15 09:30

那v.get(0)返回的是什么?

一直爬行的蜗牛 | 园豆:193 (初学一级) | 2014-05-15 23:30

v.get(0)返回的vector用一个重新分配空间的c保存,对c的修改不就是不影响v吗?

一直爬行的蜗牛 | 园豆:193 (初学一级) | 2014-05-15 23:33

@一直爬行的蜗牛:

1. 可以用指针进行理解, v.get(0)返回的是指向内存空间中c向量的地址,并没有将v中c的内容重新拷贝一份返回。见Vector.java的源代码:

   // 第728行到747行 
   @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];    // 返回的内容并没有重新进行内存分配
    }

    /**
     * Returns the element at the specified position in this Vector.
     *
     * @param index index of the element to return
     * @return object at the specified index
     * @throws ArrayIndexOutOfBoundsException if the index is out of range
     *            ({@code index < 0 || index >= size()})
     * @since 1.2
     */
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

2. 如果要改变c的内容,并不影响v的话, 可以采用clone的方式:

import java.util.*;
public class Vectorp {
    public static void main(String[] args) {
        Vector<Vector<Integer>> v = new Vector<Vector<Integer>>();
        Vector<Integer> c = new Vector<Integer>();
        c.add(1);
        c.add(2);
        c.add(3);
        v.add(c);
        System.out.println("Before: ");
        System.out.println("c value: " + c);
        System.out.println("v value: " + v);

        c = (Vector<Integer>) v.get(0).clone();
        c.remove(1);

        System.out.println("After: ");
        System.out.println("c value: " + c);
        System.out.println("v value: " + v);

    }
}
grassofsky | 园豆:342 (菜鸟二级) | 2014-05-16 09:02

@grass of moon: 回答的很好,是我自己学的不够扎实!

一直爬行的蜗牛 | 园豆:193 (初学一级) | 2014-05-16 23:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册