将对象添加到 ArrayList 并稍后对其进行修改 [英] Add an object to an ArrayList and modify it later

查看:26
本文介绍了将对象添加到 ArrayList 并稍后对其进行修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 ArrayList,并且我向它添加了一个对象,然后我修改了这个对象,这个更改会反映在 ArrayList 中吗?或者当我将对象添加到 ArrayList 时,Java 会创建一个副本并将其添加到 ArrayList?

If I have an ArrayList, and I added an object to it, and later I modified this object, will this change reflect in the ArrayList? or when I add the object to the ArrayList, Java creates a copy and add it to the ArrayList?

如果我将此对象的引用更改为 null 会怎样?这是否意味着 ArrayList 中的对象现在也为 null?

What if I change the reference to this object to null? Does that mean that the object in the ArrayList now null too?

推荐答案

此更改会反映在 ArrayList 中吗?

是的,因为您向列表中的对象添加了引用.您添加的引用仍将指向同一个对象(您修改的对象).

Yes, since you added a reference to the object in the list. The reference you added will still point to the same object, (which you modified).

或者当我将对象添加到 ArrayList 时,Java 会创建一个副本并将其添加到 ArrayList?

不,它不会复制对象.(它将复制对对象的引用.)

No, it won't copy the object. (It will copy the reference to the object.)

如果我将此对象的引用更改为空会怎样?这是否意味着 ArrayList 中的对象现在也为 null?

不,因为原始参考的内容在添加到列表时被复制.(请记住,复制的是引用,而不是对象.)

No, since the content of the original reference was copied when added to the list. (Keep in mind that it is the reference that is copied, not the object.)

演示:

StringBuffer sb = new StringBuffer("foo");

List<StringBuffer> list = new ArrayList<StringBuffer>();
list.add(sb);

System.out.println(list);   // prints [foo]
sb.append("bar");

System.out.println(list);   // prints [foobar]

sb = null;

System.out.println(list);   // still prints [foobar]

这篇关于将对象添加到 ArrayList 并稍后对其进行修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆