Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an object to an ArrayList and modify it later

Tags:

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?

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

like image 456
K'' Avatar asked Aug 16 '11 15:08

K''


People also ask

Can an object change after it has been added to an ArrayList?

Any change to the object will be reflected in the list. However, when you deal with objects like Strings that are immutable, a new object will be created on "change operations". Than actually your old object is still in the list while you got a new one elsewhere.

How do you modify an object in an ArrayList?

To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.

How do you add an object to an ArrayList of objects?

To add an object to the ArrayList, we call the add() method on the ArrayList, passing a pointer to the object we want to store. This code adds pointers to three String objects to the ArrayList... list. add( "Easy" ); // Add three strings to the ArrayList list.

How do you modify an existing ArrayList in Java?

You can use the set() method of java. util. ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, the first is the index of an element you want to replace, and the second is the new value you want to insert.


1 Answers

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] 
like image 135
aioobe Avatar answered Oct 06 '22 15:10

aioobe