Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList and modifying objects included in it

Say we have an ArrayList myArray. I want to modify an object by calling its function. If I do it this way, will the original object be changed or not?

myArray.get(0).myModyfyingFunction(); 

To clarify further - I am concerned if get() actually returns a reference to my original object or does it only return a copy of my original object.

like image 398
c0dehunter Avatar asked Mar 19 '12 17:03

c0dehunter


2 Answers

get() will return a reference to the object, never a copy. Any modification you do on the returned reference will be made on the object itself

like image 156
Óscar López Avatar answered Sep 25 '22 11:09

Óscar López


If you store any object in ArrayList, Object is not replicated and any change in object should reflect in object itself.

for example we have class NewClass

  public class NewClass {  private String mystring="";  /**  * @return the mystring  */ public String getMystring() {     return mystring; }  /**  * @param mystring the mystring to set  */ public void setMystring(String mystring) {     this.mystring = mystring; } 

}

here is code in main method of any other class

   List<NewClass> newclasses = new ArrayList<NewClass>();     NewClass class1 = new NewClass();     class1.setMystring("before1");     NewClass class2 = new NewClass();     class2.setMystring("before2");     newclasses.add(class1); newclasses.add(class2); newclasses.get(0).setMystring("after1"); System.out.println(class1.getMystring()); 

This will output after1.

like image 30
kundan bora Avatar answered Sep 23 '22 11:09

kundan bora