加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

用Java分配运算符

发布时间:2020-12-15 02:49:25 所属栏目:Java 来源:网络整理
导读:我在 Java中有2个ArrayLists: mProductList = new ArrayListProductSample();mProductList2 = new ArrayListProductSample();mProductList = productSampleList;mProductList2 = productSampleList;mProductList2 .remove(3); productSampleList的大小为5.
我在 Java中有2个ArrayLists:
mProductList = new ArrayList<ProductSample>();
mProductList2 = new ArrayList<ProductSample>();

mProductList = productSampleList;

mProductList2 = productSampleList;

mProductList2 .remove(3);

productSampleList的大小为5.
为什么在执行此段代码之后. mProductList的大小是4?

我们有办法避免这种情况吗?我希望mProductList的大小为5,与productSampleList相同.
谢谢!

解决方法

试试这个:
mProductList2 = new ArrayList<ProductSample>(productSampleList);

就像目前一样,productSampleList,mProductList和mProductList2都指向同一个对象,因此对其他对象的更改将反映在其他对象上.我的解决方案是简单地创建一个可以独立于原始文件修改的列表副本,但请记住:productSampleList和mProductList仍然指向同一个对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读