How do I use an equivalent to C++ reference parameters in Java?

后端 未结 11 1328
借酒劲吻你
借酒劲吻你 2020-12-09 14:33

Suppose I have this in C++:

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

The values are altered inside the function and then use

11条回答
  •  旧巷少年郎
    2020-12-09 14:53

    You could construct boxed objects, ie,

    Integer iObj = new Integer(i);
    Integer jObj = new Integer(j);
    

    and write your routine as

    public void test(Integer i, Integer j){
      i = i.add(1);
      j = j.add(1);
    }
    

    For any number of reasons, the designers of Java felt call-by-value was better; they purposefully didn't include a method for call by reference. (Strictly, they pass copies of references to the objects, with the special case for the primitive types that they are purely call by value. But the effect is the same.)

提交回复
热议问题