Data Structures Part 2-lesson 18

Hello everyone, there’s one thing I don’t get when I take lesson 18 of data structures and algorithm.
I thought when we pass arguments to a function, we pass the arguments by value, not by reference. Therefore, no matter what you do to the arguments inside the function, it’s “basically” not changing the the arguments outside the function.

We pass an ArrayList called list to the private getNodesAtDistance function.
Theoretically, the list inside the function should be another copy of the list outside the function.
Then on line 193, when we add a new item to the list inside the function, why can it change the list outside the function?

I’m not sure if you are familiar with the concepts of primitive types and reference types in Java. For primitive types the value passed is the actual value while it’s an address / reference for reference types. So you can change the content (members) of reference type arguments.

Note that strings are reference types but behave a lot like value types because they are immutable.

1 Like

I tried to write similar code in Swift version. I also passed an array to a function, and tried to manipulate the array inside the function, such as adding a new item to the array. However, it said that I couldn’t, because it was a constant. (I originally declared that array as a variable outside the function).

I guess something is different among languages?

I never coded in Swift so I can’t really help with that. Just a few pointers: AFAIK in Swift arrays are value types. To achieve a similar behaviour to the java code you could have a look if the framework provides a collection similar to the ArrayList (the list parameter in the example above is not an array) in Java. Or you could try to override the default value passing behaviour. Many languages have modifiers for parameters like ref, inout. etc. that pass arguments by reference instead of by value.

1 Like