How do I use an equivalent to C++ reference parame

2020-02-04 06:07发布

Suppose I have this in C++:

void test(int &i, int &j)
{
    ++i;
    ++j;
}

The values are altered inside the function and then used outside. How could I write a code that does the same in Java? I imagine I could return a class that encapsulates both values, but that seems really cumbersome.

11条回答
乱世女痞
2楼-- · 2020-02-04 07:06

A better question: why are you creating methods with such side-effects?

Generally, this is a strong indication that you should extract the data into a separate class, with public accessors that describe why the operation is taking place.

查看更多
够拽才男人
3楼-- · 2020-02-04 07:07

Java does not have pass-by-reference. You must encapsulate to achieve the desired functionality. Jon Skeet has a brief explanation why pass-by-reference was excluded from Java.

查看更多
劫难
4楼-- · 2020-02-04 07:07

Well, there are a couple of workarounds. You mentioned one yourself. Another one would be:

public void test(int[] values) {
    ++values[0];
    ++values[1];
}

I would go with the custom object, though. It’s a much cleaner way. Also, try to re-arrange your problem so that a single method doesn’t need to return two values.

查看更多
Lonely孤独者°
5楼-- · 2020-02-04 07:10

Java has no equivalent of C++ references. The only way to get this to work is to encapsulate the values in another class and swap the values within the class.

Here is a lengthy discussion on the issue: http://www.yoda.arachsys.com/java/passing.html

查看更多
地球回转人心会变
6楼-- · 2020-02-04 07:11

Java passes parameters by value, and has no mechanism to allow pass-by-reference.

查看更多
登录 后发表回答