ArrayList.add

API: arrayList.set(i, element)

when coding, update the condition in the while loop so that it won’t go to infinite loop.

http://stackoverflow.com/questions/7080546/add-an-object-to-an-arraylist-and-modify-it-later

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]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s