Does modifying the result of a getter affect the object itself?

Jordanss10 picture Jordanss10 · Jun 4, 2013 · Viewed 10.7k times · Source

I have a question about using getter methods in java. Suppose I had this class:

class Test {
    private ArrayList<String> array = new ArrayList<String>();

    public ArrayList getArray() {
        return this.array;
    }

    public void initArray() {
        array.add("Test 1");
        array.add("Test 2");
    }
}

class Start {
    public static void main(String args[]) {
        initArray();
        getArray().remove(0);
    }
} 

My question is:

Would the actual arraylist object be modified ("Test 1" removed from it)? I think I have seen this in places, but I thought that getters were simply providing a copy of that object. Not a reference to it. If it did work that way (as a reference), then would this work as well (Would the arraylist object of the class Test be altered by this as well)?:

class Start {
    public static void main(String args[]) {
        initArray();
        ArrayList aVar = getArray();
        aVar.remove(0);
    }
} 

Answer

greedybuddha picture greedybuddha · Jun 4, 2013

Java returns references to the Array, so it won't be a copy and it will modify the List. In general, unless its a primitive type (int,float,etc) you will be getting a reference to the object.

You have to explicitly copy the array yourself if you want a duplicate to be returned.