I have read Jon Skeet's [excellent] article about passing values in Java and seen this question on the same topic. I believe I understand them but what I am still wondering about is return values.
When an object is returned (as from a getter) then later altered in it's original scope (where it was gotten from) is the object reference owned by the variable to which the getter's return value was assigned altered? Boy that was a mouthful..
To borrow an example:
public class Dog {
String dog ;
public String getName()
{
return this.dog;
}
public Dog(String dog)
{
this.dog = dog;
}
public void setName(String name)
{
this.dog = name;
}
public static void main(String args[])
{
Dog myDog = new Dog("Rover");
String dogName = myDog.getName();
myDog.setName("Max");
System.out.println(dogName);
}
}
Does that print Rover or Max?
UPDATE Does print Rover.
The answers to my original question were great but Richard Tingle added a lot of useful information in the comments below so I thought I'd provide my test class for posterity.
public class Foo {
private ArrayList<Integer> arrayList;
public Foo() {
arrayList = new ArrayList<Integer>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
}
public ArrayList<Integer> getArrayList() {
return arrayList;
}
public void addToArrayList(int item) {
arrayList.add(item);
}
public static void main(String args[]) {
Foo foo = new Foo();
ArrayList<Integer> arrayList = foo.getArrayList();
ArrayList<Integer> cloneList = (ArrayList<Integer>)foo.getArrayList().clone();
System.out.println(arrayList.contains(4));
System.out.println(cloneList.contains(4));
foo.addToArrayList(4);
System.out.println(arrayList.contains(4));
System.out.println(cloneList.contains(4));
}
Output is false
, false
, true
, false