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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With