Java 复制 ArrayList 值不是引用

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}]

为什么会这样?我怎么能阻止它?


慕盖茨4494581
浏览 134回答 3
3回答

慕工程0101907

如果你想复制一个列表,我建议使用Collections.copy:List<UserPhoto> copiedList = new ArrayList<UserPhoto>();Collections.copy(copiedList, loggedUserAuthResource.data.getUserPhotos());&nbsp;copiedList.add(new UserPhoto("ADD"));您的getUserPhotos()方法可能仍然引用源列表。

30秒到达战场

在这里你不复制任何东西:List<UserPhoto>&nbsp;copiedList&nbsp;=&nbsp;loggedUserAuthResource.data.getUserPhotos();您使copiedList变量引用与引用相同的List实例。loggedUserAuthResource.data.getUserPhotos()因此它将对象添加到List存在的单个实例中:copiedList.add(new&nbsp;UserPhoto("ADD"));ArrayList您想要的是从现有对象(复制构造函数)创建一个新对象。这样你就有了两个不同的列表对象,你只能在这个新的中添加新元素ArrayList:List<UserPhoto>&nbsp;copiedList&nbsp;=&nbsp;new&nbsp;ArrayList<>(loggedUserAuthResource.data.getUserPhotos()); copiedList.add(new&nbsp;UserPhoto("ADD")));

红糖糍粑

您也可以这样做。List<UserPhoto> copiedList = new ArrayList<UserPhoto>(); copiedList.addAll(loggedUserAuthResource.data.getUserPhotos()); copiedList.add(new UserPhoto("ADD"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java