0

In the code below, I am attempting to create a mutator method that alters the input List. When I write the same code, and do not use a method, it works and prints Mouse. However, when I create the mutate method below, House is printed rather than Mouse. Please explain why the line inputList = temp isn't working.

public class Demo {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("House");
        mutate(list);
        System.out.println(list);
    }

    public static void mutate(List<String> inputList){
        List<String> temp = new ArrayList<String>();
        temp.add("Mouse");
        inputList = temp;
    }
}
Dmitriy
  • 5,525
  • 12
  • 25
  • 38
krohn
  • 13
  • 4
  • 4
    this might help you to understand what is going on http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1 – matoni Jan 30 '16 at 22:23

1 Answers1

2

Java is a pass-by-value language.

People will sometimes claim (wrongly) that it's a pass-by-reference language, because all objects are referred to via references, so the values that you pass around are references; but a parameter like inputList is nonetheless a local variable, so assigning to it (inputList = ...) only affects that local variable. It's not an alias of any variable in the calling method.

However, you can certainly mutate the specific ArrayList instance that inputList refers to:

public static void mutate(final List<String> inputList){
    inputList.clear();
    inputList.add("Mouse");
}
ruakh
  • 175,680
  • 26
  • 273
  • 307