Java增强的For循环:引用的集合未更改

gen*_* b. 1 java

有些奇怪的事情发生了,假设我的代码带有'Attachment'对象,我想将所有对象设置为NULL.

List<Attachment> attachments = getAttachments();

for (Attachment attachment: attachments)
{
   attachment = null;
}
Run Code Online (Sandbox Code Playgroud)

立即对象附件成功设置为NULL.但是支持系列没有受到影响.它仍然有旧数据.我以为我们总能依赖Java中的引用?

rge*_*man 8

是的,如果您正确理解它们,您可以依赖Java中的引用.您有一个引用变量attachment,但它是引用您要设置的对象的2个引用之一null.

attachments -> { Attachment, Attachment, Attachment }
                     |           |           |
                     v           v           v
  attachment -->  (object)    (object)    (object)
Run Code Online (Sandbox Code Playgroud)

分配null给时attachment,列表引用不会更改.

attachments -> { Attachment, Attachment, Attachment }
                     |           |           |
                     v           v           v
  attachment      (object)    (object)    (object)
      |
      v
    (null)
Run Code Online (Sandbox Code Playgroud)

增强的for循环不允许您以这种方式更改列表内容.

您可以使用传统的for循环,并调用set:

for (int i = 0; i < attachments.size; i++)
{
    attachments.set(i, null);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,目前还不清楚为什么要设置所有元素null.这留下了列表中的n份副本null.另一种方法是删除对列表的所有引用,在列表中attachments.clear()根本不会引用任何引用,即使null这是您真正想要做的事情.