Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

java - Add an object to an ArrayList and modify it later

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...