Friday, October 26, 2018

java - pass by reference/value - simple example



I know this issue has been addressed many times - but my Java/C++ knowledge is so weak I can barely understand the answers :-( ... what I'd really like is just a super simple example.



In C++ I could write the following:




void func()
{
int x = 3;
add_one(x);
// now x is 4.
}
void add_one(int &var)
{
var++;
}



What I'd like to see now is the simplest way to achieve the same effect with java.


Answer



You can't directly. The closest you can get is to put the value in an object, and pass the reference (by value, so the reference gets copied) into the method.



void func()
{
int x = 3;
int[] holder = [x];

add_one(holder);
// now holder[0] is 4. x is still 3.
}

// container here is a copy of the reference holder in the calling scope.
// both container and holder point to the same underlying array object
void add_one(int[] container)
{
container[0]++;
}



Here I use an array, but the wrapper can be any object.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...