Java中的赋值运算符

6

I have 2 ArrayLists in Java:

mProductList = new ArrayList<ProductSample>();
mProductList2 = new ArrayList<ProductSample>();

mProductList = productSampleList;

mProductList2 = productSampleList;

mProductList2 .remove(3);

productSampleList的大小为5。为什么执行这段代码后,mProductList的大小变成了4?

我们有没有办法避免这种情况发生?我希望mProductList的大小能像productSampleList一样是5。
谢谢!

4个回答

9

试试这个:

mProductList2 = new ArrayList<ProductSample>(productSampleList);

目前,productSampleListmProductListmProductList2 指向同一对象,因此对其中一个对象的更改将反映在其他对象上。我的解决方案是创建一个列表的副本,可独立于原始列表进行修改,但请记住:productSampleListmProductList 仍指向同一对象。


@VanDang 不是的,你在 mProductList2 = productSampleList; 这一行重新将 mProductList2 分配给了一个不同的列表。你必须理解Java中对象引用的概念。 - Óscar López
我明白了!非常感谢您的帮助!我是Java的新手,所以这个错误是不可避免的。再次感谢。 - Ngo Van

4
所有3个productSampleList, mProductListmProductList2都是指向同一个ArrayList对象的引用,因此调用任何一个中的.remove()方法都会从底层单个的ArrayList对象中移除元素。
如果您想为每个变量保留单独的ArrayList引用,您需要创建3个不同的ArrayList

2
你可以尝试这个方法:-
    public class ArrayListTest {

    public static void main(String str[]){
        ArrayList productSampleList=new ArrayList();
        ArrayList mProductList=null;
        ArrayList mProductList2=null;

        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");
        productSampleList.add("Hi");

        System.out.println("Main productSampleList size..."+productSampleList.size());
        mProductList=new ArrayList(productSampleList);
        mProductList2=new ArrayList(productSampleList);
        System.out.println("mProductList size..."+mProductList.size());
        System.out.println("mProductList2 size..."+mProductList2.size());
        mProductList2.remove(1);
        System.out.println("mProductList size..."+mProductList.size());
        System.out.println("mProductList2 size..."+mProductList2.size());

    }
}

输出:

Main productSampleList size...5

mProductList size...5

mProductList2 size...5

mProductList size...5

mProductList2 size...4

2
当您使用列表(或ArrayList)时,size()方法返回列表中元素的数量。列表不像数组那样大小是固定的。如果您想要一个固定的大小,请使用数组。
请查看http://docs.oracle.com/javase/7/docs/api/java/util/List.html了解更多关于列表的信息。 这里有一个很好的区分数组和ArrayList的文章。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接