1

Let's say I initialise my list like so:

public static void main(String[] args) {
    ArrayList<String> a = new ArrayList<String>();
    a.add("one");
    a.add("two");
    a.add("three");
    a.add("four");
    modifyList(a);
}

where modifyList simply changes every value to "one" like so:

private static void modifyList(ArrayList<String> a) {
    for (int i = 0; i < a.size(); i++) {
        a.set(i, "one");
    }
}

If I print the list before and after I call this method, I expect the same original list to appear twice. But for some reason, the ArrayList that gets modified in modifyList is the same as the ArrayList in main.

If I try the same experiment with ints and Strings instead of Lists they do not get modified.

Can anyone explain why?

Jason
  • 11,744
  • 3
  • 42
  • 46
eyes enberg
  • 556
  • 1
  • 8
  • 30

1 Answers1

4

In Java, parameters are passed by value.

However, you passed a reference to your ArrayList to the method (and the reference itself is passed by value), and therefore the method modified the original list.

If you want to ensure that this cannot happen, you need to pass an immutable list as the parameter.

Jason
  • 11,744
  • 3
  • 42
  • 46
  • If that's the case, then when I use ints and strings am I not passing the reference of an Integer/String object to a method instead of it's value (the same way I pass the reference of an ArrayList instead of it's values)? – eyes enberg Apr 03 '16 at 22:52
  • You should show the code for the experiments that do not behave as you expect. There's a difference between integers and Integers, believe it or not (actually ints and Integers), and we cannot tell what you did for sure from your description. – arcy Apr 03 '16 at 22:55
  • There is a difference between Java primitives (int , float , byte , char etc) and Java objects (with the exception of String, which is an object that is treated as a primitive). Primitives are passed by value and are immutable. So when you try changing primitives, a new value gets created instead of original one changing. However objects are passed around by reference to original obj, therefore any changes that are made to it affects the original value. – mmaarouf Apr 03 '16 at 23:07
  • 1
    @eyesenberg If you pass an `Integer`, then you pass a reference to that Integer object by value. If you pass an `int` then you pass the value. These are two different cases. Note that Strings, Integers and other primitive-like classes are built to be immutable. – Tassos Bassoukos Apr 03 '16 at 23:07
  • Ah OK this clears everything up. Thanks to all. – eyes enberg Apr 03 '16 at 23:27