Is it ok to pass an array as an argument in java like this
I want to pass the reference to the array because I want to change the array in the calling function. What would be the syntax?
Arrays are objects in Java. And references to objects are passed by value.
In Java, an array is passed by reference, but the reference is passed by value. Suppose you have an array
You can see from the example that
For more reference see this:
Java is pass by value. This reference will be passed by value, that is copied. It will still point at the original array.
Could change your function parameter to accept an List?
The static method asList from java.util.Arrays should return a List that uses the array as storage.
I will review this later.
This might be an unpopular way of thinking about it, but being from a C/C++ side myself, it made it easier for me.
In Java, objects are reference types. Meaning that the actual object is on the heap somewhere, and what you actually use is just a reference to that object. Thus it is simpler to think of it in terms of C pointers (as an analogy).
would behave similar to the below in C/C++
Similarly, in the case of functions, they behave as if the parameters of the function are passed as pointers. Similar to how you would simulate pass-by-reference in C
Is more like the below C version
and as long as you dont change the value of the pointer itself (in java by reallocating the variable with a new instance) you can use it to access and modify the original instance.
And to wrap it all up, ALL types other than the primitive types (
So as others have explained already, you dont need to add the