亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 253 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號