对象添加到一个ArrayList和以后修改 [英] Add an object to an ArrayList and modify it later

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

问题描述

如果我有一个ArrayList,和我添加了一个对象吧,后来我修改这个对象,将这一变化ArrayList中体现?或当我的对象添加到ArrayList中,Java的创建副本,并将其添加到ArrayList <?/ p>

如果我改变引用该对象为null?这是否意味着,在ArrayList中的对象现在空了吗?


解决方案

  

将这种变化反映了ArrayList的?


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



  

或当我对象添加到ArrayList中,Java的创建副本,并将其添加到ArrayList


没有,也不会复制的对象。 (这将复制参考的对象。)



  

如果我改变引用该对象为null?这是否意味着,在ArrayList中的对象现在空了吗?


没有,因为原来的基准的含量为复制的当加入到列表中。 (请记住,它是复制,而不是对象的参考的。)

演示:

 的StringBuffer某人=新的StringBuffer(富);清单&LT;&的StringBuffer GT;名单=新的ArrayList&LT;&的StringBuffer GT;();
list.add(某人);的System.out.println(名单); //输出[富]
sb.append(巴);的System.out.println(名单); //输出[foobar的]SB = NULL;的System.out.println(名单); //仍然打印[foobar的]

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?

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

解决方案

will this change reflect in the 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).


or when I add the object to the ArrayList, Java creates a copy and add it to the ArrayList?

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


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

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.)

Demonstration:

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天全站免登陆