为了账号安全,请及时绑定邮箱和手机立即绑定

Java 复制 ArrayList 值不是引用

Java 复制 ArrayList 值不是引用

慕盖茨4494581 2023-06-08 19:44:49
Log.d(TAG, "onChanged: " + loggedUserAuthResource.data.getUserPhotos());List<UserPhoto> copiedList = loggedUserAuthResource.data.getUserPhotos();copiedList.add(new UserPhoto("ADD"));Log.d(TAG, "onChanged: " + copiedList);Log.d(TAG, "onChanged: " + loggedUserAuthResource.data.getUserPhotos());如您所见,我只想将一个项目添加到我复制的列表中,但它也会添加到 loggedUserAuthResource 列表中。2019-08-18 15:06:18.104 8151-8151/ D/EditProfileActivity: onChanged: [UserPhoto{photoName='110ab4146695a093834701640fcee83c_y.jpg', orderId=1}, UserPhoto{photoName='59b7ee6ad3107d83227d017c45ffc899_y.jpg', orderId=2}, UserPhoto{photoName='90ae37db9a5d44026ebad8f622bf2c59_y.jpg', orderId=3}, UserPhoto{photoName='d2f7968640ebb4260b5e5dd1a10c1efd_y.jpg', orderId=4}, UserPhoto{photoName='e792f85d4f53a777f4399fe79f8edd99_y.jpg', orderId=5}, UserPhoto{photoName='22f943f0507223ce31fa1ca3c0e61b32_y.jpg', orderId=6}, UserPhoto{photoName='8b19b52c1482c522be21151eb4eb8009_y.jpg', orderId=7}]2019-08-18 15:06:18.104 8151-8151/ D/EditProfileActivity: onChanged: [UserPhoto{photoName='110ab4146695a093834701640fcee83c_y.jpg', orderId=1}, UserPhoto{photoName='59b7ee6ad3107d83227d017c45ffc899_y.jpg', orderId=2}, UserPhoto{photoName='90ae37db9a5d44026ebad8f622bf2c59_y.jpg', orderId=3}, UserPhoto{photoName='d2f7968640ebb4260b5e5dd1a10c1efd_y.jpg', orderId=4}, UserPhoto{photoName='e792f85d4f53a777f4399fe79f8edd99_y.jpg', orderId=5}, UserPhoto{photoName='22f943f0507223ce31fa1ca3c0e61b32_y.jpg', orderId=6}, UserPhoto{photoName='8b19b52c1482c522be21151eb4eb8009_y.jpg', orderId=7}, UserPhoto{photoName='ADD', orderId=0}]为什么会这样?我怎么能阻止它?
查看完整描述

3 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

如果你想复制一个列表,我建议使用Collections.copy:


List<UserPhoto> copiedList = new ArrayList<UserPhoto>();

Collections.copy(copiedList, loggedUserAuthResource.data.getUserPhotos()); 

copiedList.add(new UserPhoto("ADD"));

您的getUserPhotos()方法可能仍然引用源列表。


查看完整回答
反对 回复 2023-06-08
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

在这里你不复制任何东西:

List<UserPhoto> copiedList = loggedUserAuthResource.data.getUserPhotos();

您使copiedList变量引用与引用相同的List实例。loggedUserAuthResource.data.getUserPhotos()

因此它将对象添加到List存在的单个实例中:

copiedList.add(new UserPhoto("ADD"));

ArrayList您想要的是从现有对象(复制构造函数)创建一个新对象。这样你就有了两个不同的列表对象,你只能在这个新的中添加新元素ArrayList

List<UserPhoto> copiedList = new ArrayList<>(loggedUserAuthResource.data.getUserPhotos());
copiedList.add(new UserPhoto("ADD")));


查看完整回答
反对 回复 2023-06-08
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

您也可以这样做。

List<UserPhoto> copiedList = new ArrayList<UserPhoto>();
copiedList.addAll(loggedUserAuthResource.data.getUserPhotos());
copiedList.add(new UserPhoto("ADD"));


查看完整回答
反对 回复 2023-06-08
  • 3 回答
  • 0 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信